Introduction to Python Sets
You already know lists, tuples, and dictionaries. Sets are Python's fourth built-in collection. They store only unique values, ignore duplicates automatically, and make membership checks lightning fast. This lesson shows you how to create sets, convert lists into sets, and test whether a value exists.
Sets are Python's built-in collection for storing unique values. Unlike lists, sets cannot contain duplicates and have no fixed order.
You create a set with curly braces, similar to a dictionary but without key-value pairs.
The syntax for creating a set:
Duplicates are removed automatically. Even though we wrote six values, the set keeps only three.
What will be the output?
To create an empty set, use set(). Writing {} creates an empty dictionary instead.
Empty set vs empty dictionary:
You can also create a set from a list using set(). This removes all duplicates.
What will be the output?
You can check if a value exists in a set using the in keyword, just like with lists.
Membership checks with in are very fast on sets, even with millions of elements.
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?