Python Tutorial menu

Python Sets

A set is a collection that keeps only unique items and has no fixed order.

Creating a Set

Write the items inside curly brackets {}:

Example

python
colors = {"red", "green", "blue", "red"}
print(colors)
print(len(colors))
Output
{'green', 'red', 'blue'}
3

The second "red" disappeared because sets do not allow duplicates. The order you see may be different on your computer, because sets are unordered.

To create an empty set, write set(). Writing {} creates an empty dictionary, not a set.

Removing Duplicates From a List

A very common use of sets is to remove repeated values:

Example

python
cities = ["Karachi", "Lahore", "Karachi", "Quetta", "Lahore"]
unique = set(cities)
print(len(unique))
print(sorted(unique))
Output
3
['Karachi', 'Lahore', 'Quetta']

No Indexing

Because sets have no order, you cannot use colors[0]. Instead, loop through the set or check if an item is in it:

Example

python
colors = {"red", "green"}
print("red" in colors)
for c in sorted(colors):
    print(c)
Output
True
green
red

Adding and Removing Items

Example

python
skills = {"Python", "Excel"}
skills.add("SQL")
skills.update(["Git", "HTML"])
skills.remove("Excel")
skills.discard("Java")    # no error even though Java is not there
print(sorted(skills))
Output
['Git', 'HTML', 'Python', 'SQL']

remove() raises an error if the item is missing. discard() does not.

Set Operations

Sets are great for comparing two groups. Imagine two classes at an institute:

Example

python
morning = {"Ali", "Sara", "Hamza", "Zainab"}
evening = {"Hamza", "Zainab", "Bilal"}

print(sorted(morning.union(evening)))
print(sorted(morning.intersection(evening)))
print(sorted(morning.difference(evening)))
print(sorted(morning.symmetric_difference(evening)))
Output
['Ali', 'Bilal', 'Hamza', 'Sara', 'Zainab']
['Hamza', 'Zainab']
['Ali', 'Sara']
['Ali', 'Bilal', 'Sara']
MethodResultShort symbol
union()Items in either set(pipe symbol)
intersection()Items in both sets&
difference()Items in the first set only-
symmetric_difference()Items in one set but not both^

For example, morning & evening gives the same result as morning.intersection(evening).

Frozen Sets

A frozenset is a set that cannot be changed after it is created, just like a tuple compared to a list:

Example

python
weekend = frozenset(["Sat", "Sun"])
print("Sun" in weekend)
Output
True

Exercise

Exercise

What does len({1, 2, 2, 3, 3, 3}) return?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp