set() removes duplicates from whatever iterable you pass it, since a set can only contain each distinct value once, and it requires every element to be hashable, so lists and dicts can't be set members, but tuples and strings can. Sets support fast membership testing in average constant time, and mathematical operations like union, intersection, and difference.
1Understanding set()
set() removes duplicates from whatever iterable you pass it, since a set can only contain each distinct value once, and it requires every element to be hashable, so lists and dicts can't be set members, but tuples and strings can. Sets support fast membership testing in average constant time, and mathematical operations like union, intersection, and difference.
Calling set() with no arguments makes an empty set — but a pair of empty curly braces makes an empty dict instead, because that syntax was already reserved for dict literals before set literals existed.
numbers = [1, 2, 2, 3, 3, 3]
unique = set(numbers)
print(unique)2Practical Example
Here is a real-world application of set() showing how it is used in production Python code.
admins = {"alice", "bob"}
online = {"bob", "carol"}
print(admins & online)
print(admins | online)3Best Practices
Follow these guidelines when working with set():
1. Use set(iterable) to quickly deduplicate a list while discarding order
2. Use set intersection/union/difference operators instead of manual loops when comparing two collections
3. Remember sets are unordered — sort the result if you need a predictable, ordered output
Tip: Calling set() with no arguments makes an empty set — but a pair of empty curly braces makes an empty dict instead, because that syntax was already reserved for dict literals before set literals existed.
numbers = [1, 2, 2, 3, 3, 3]
unique = set(numbers)
print(unique)