A Set in Python (programming language) is a collection used to store multiple unique items in a single variable.

Unlike lists or tuples, sets:

  • Do not allow duplicate values
  • Are unordered
  • Cannot access items using index
  • Are mutable (you can add or remove items)

Sets are created using curly braces {}.


1️⃣ Creating a Set

numbers = {1, 2, 3, 4, 5}
print(numbers)

Output (order may vary)

{1, 2, 3, 4, 5}

2️⃣ Duplicate Values Are Removed

Sets automatically remove duplicates.

numbers = {1, 2, 2, 3, 4, 4, 5}
print(numbers)

Output

{1, 2, 3, 4, 5}

3️⃣ Set with Different Data Types

A set can contain different data types.

data = {10, "Python", 3.14, True}
print(data)

Example Output

{10, 3.14, 'Python', True}

4️⃣ Accessing Set Items

Sets are unordered, so items cannot be accessed by index.
You must use a loop to access items.

fruits = {"apple", "banana", "cherry"}

for fruit in fruits:
print(fruit)

5️⃣ Adding Items to a Set

add()

Adds a single item.

fruits = {"apple", "banana"}

fruits.add("mango")

print(fruits)

Output

{'apple', 'banana', 'mango'}

update()

Adds multiple items.

fruits = {"apple", "banana"}

fruits.update(["orange", "grapes"])

print(fruits)

6️⃣ Removing Items

remove()

Removes a specific item.

fruits = {"apple", "banana", "cherry"}

fruits.remove("banana")

print(fruits)

discard()

Removes an item but does not raise an error if the item is not found.

fruits.discard("banana")

7️⃣ Set Length

Use len() to find number of items.

fruits = {"apple", "banana", "cherry"}

print(len(fruits))

Output

3

8️⃣ Set Union

Combines two sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}

result = set1.union(set2)

print(result)

Output

{1, 2, 3, 4, 5}

9️⃣ Set Intersection

Returns common elements.

set1 = {1, 2, 3}
set2 = {2, 3, 4}

print(set1.intersection(set2))

Output

{2, 3}

πŸ”Ÿ Clearing a Set

numbers = {1, 2, 3}

numbers.clear()

print(numbers)

Output

set()

⭐ Summary

FeatureSet
Ordered❌ No
Duplicate values❌ Not allowed
Mutableβœ… Yes
Syntax{ }

βœ… Example Program

fruits = {"apple", "banana", "cherry"}

fruits.add("mango")

for fruit in fruits:
print(fruit)