Collections

Sets

Sets store unique values and make membership checks explicit.

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']
KEYS ONLYabcx in sO(1)
Sets are hash buckets without values; `x in s` averages O(1) regardless of size.

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
False

Union, 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

See also

Run the complete example

Example code

Expected output

['go', 'python']
True
False
['go', 'python', 'rust']
['rust']
['python']

Execution time appears here after you run the example.