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
| Feature | Set |
|---|---|
| Ordered | β No |
| Duplicate values | β Not allowed |
| Mutable | β Yes |
| Syntax | { } |
β Example Program
fruits = {"apple", "banana", "cherry"}
fruits.add("mango")
for fruit in fruits:
print(fruit)