Collections
Sets
Creating a set removes duplicates. Keep a list when order and repeated values matter; convert to a set when uniqueness is the point.
Source
languages = ["python", "go", "python"]
unique_languages = set(languages)
print(sorted(unique_languages))Output
['go', 'python']Membership checks are the everyday set operation. A list can also use in, but a set says that membership is central to the data shape.
Source
allowed = {"python", "rust"}
print("python" in allowed)
print("ruby" in allowed)Output
True
FalseUnion, intersection, and difference describe relationships between groups without manual loops.
Source
compiled = {"go", "rust"}
print(sorted(allowed | compiled))
print(sorted(allowed & compiled))
print(sorted(allowed - compiled))Output
['go', 'python', 'rust']
['rust']
['python']Notes
- Use lists when order and repeated values matter.
- Use sets when uniqueness and membership are the main operations.
- Prefer lists when order or repeated values are part of the meaning.
- Sets are unordered, so sort them when examples need deterministic display.
See also
- related: Lists
- related: Dictionaries
- related: Comprehensions
Run the complete example
Expected output
['go', 'python']
True
False
['go', 'python', 'rust']
['rust']
['python']
Execution time appears here after you run the example.