Python Sets
What is a Set in Python?
A set is a collection which is unordered, unindexed, and does not allow duplicate values. Sets are written with curly brackets {}
.
Key Features of Sets:
- Unordered: No guaranteed order of elements.
- Unindexed: You cannot access items via index.
- No duplicate values.
- Mutable: You can add or remove items.
Creating a Set
# Creating a set
fruits = {"apple", "banana", "cherry"}
print(fruits)
Output:
{'banana', 'apple', 'cherry'}
Note: Order may vary.
Duplicate Values Are Ignored
fruits = {"apple", "banana", "apple", "cherry"}
print(fruits)
Output:
{'banana', 'apple', 'cherry'}
Duplicate "apple"
is automatically removed.
Check if Item Exists
fruits = {"apple", "banana", "cherry"}
print("banana" in fruits)
Output:
True
Add Items to a Set
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits)
Output:
{'banana', 'apple', 'cherry'}
Add Multiple Items using update()
fruits = {"apple", "banana"}
fruits.update(["cherry", "mango"])
print(fruits)
Output:
{'banana', 'apple', 'cherry', 'mango'}
Remove Items from a Set
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
Output:
{'apple', 'cherry'}
If item not found, remove()
raises an error. Use discard()
to avoid this.
fruits.discard("orange") # No error even if 'orange' is not present
Loop Through a Set
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Order may vary.
Set Length
fruits = {"apple", "banana", "cherry"}
print(len(fruits))
Output:
3
Combine Two Sets using union()
a = {"apple", "banana"}
b = {"cherry", "banana"}
result = a.union(b)
print(result)
Output:
{'banana', 'apple', 'cherry'}
Keep Only Duplicates using intersection()
a = {"apple", "banana"}
b = {"banana", "cherry"}
result = a.intersection(b)
print(result)
Output:
{'banana'}
Keep All Except Duplicates using symmetric_difference()
a = {"apple", "banana"}
b = {"banana", "cherry"}
result = a.symmetric_difference(b)
print(result)
Output:
{'apple', 'cherry'}
Set Methods Summary
Method | Description |
---|---|
add() | Adds an item |
remove() | Removes item; error if not present |
discard() | Removes item; no error if not found |
clear() | Removes all items |
union() | Returns union of sets |
intersection() | Returns intersection |
difference() | Returns difference |
symmetric_difference() | Returns non-common items |
update() | Updates set with others |
pop() | Removes a random item |
copy() | Returns a shallow copy |
Set Exercises (Practice)
# Exercise: Remove duplicates from a list using set
my_list = [1, 2, 2, 3, 4, 4, 5]
unique = set(my_list)
print(unique)
Output:
{1, 2, 3, 4, 5}