CodeMIRAI
0 XP

Sets

2 min read 6 runnable examples Quiz included

A set is an unordered collection of unique items, written in curly braces.

Python
languages = {"Python", "Java", "Python", "C++", "Java"}
print(languages)
print(len(languages))

The duplicates disappeared: a set keeps only one of each value. Sets have no order, so they print in whatever order Python stores them, and you cannot index them (languages[0] is an error).

Removing duplicates

The quickest way to remove duplicates from a list is to turn it into a set:

Python
visits = ["home", "about", "home", "blog", "about", "home"]
unique_pages = set(visits)
print(unique_pages)
print(len(unique_pages), "unique pages")
print(sorted(unique_pages))     # back to a sorted list

Adding and removing

Python
tags = {"python", "beginner"}
tags.add("tutorial")
tags.add("python")          # already there: nothing happens
print(tags)

tags.remove("beginner")     # error if missing
tags.discard("missing")     # no error if missing
print(tags)

Fast membership tests

Checking x in some_set is extremely fast, even for millions of items, because sets use hashing. For large collections where you only need "is it there?", a set beats a list.

Python
banned = {"spam", "scam", "free money"}
for subject in ["hello", "free money", "meeting"]:
    print(subject, "->", "blocked" if subject in banned else "ok")

Set operations

Sets support the operations from maths:

Python
python_devs = {"Asha", "Leo", "Mei", "Raj"}
java_devs = {"Leo", "Raj", "Sofia"}

print(python_devs | java_devs)    # union: in either
print(python_devs & java_devs)    # intersection: in both
print(python_devs - java_devs)    # difference: Python but not Java
print(python_devs ^ java_devs)    # symmetric difference: in exactly one

The same operations exist as methods: union(), intersection(), difference(), symmetric_difference().

Subsets

Python
required = {"id", "name"}
provided = {"id", "name", "email"}
print(required <= provided)      # is required a subset of provided?
print(required.issubset(provided))

Sets can only hold immutable items (numbers, strings, tuples), not lists or other sets.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.