Python Basics — Creating Sets
Creating Sets
A set is an unordered collection where every element is unique. Duplicate values are automatically removed.
Set Literal Syntax
fruits = {"apple", "banana", "cherry"}
print(fruits) # {'cherry', 'banana', 'apple'} — order may vary
print(type(fruits)) # <class 'set'>
Automatic Deduplication
numbers = {1, 2, 3, 2, 1, 4, 3}
print(numbers) # {1, 2, 3, 4}
set() Constructor
# From a list
from_list = set([1, 2, 3, 2, 1])
print(from_list) # {1, 2, 3}
# From a string
from_string = set("hello")
print(from_string) # {'h', 'e', 'l', 'o'}
# From a tuple
from_tuple = set((1, 2, 3))
print(from_tuple) # {1, 2, 3}
# From a range
from_range = set(range(5))
print(from_range) # {0, 1, 2, 3, 4}
Empty Set
This is a common gotcha — {} creates an empty dict, not a set:
# ❌ This is a dict!
empty_dict = {}
print(type(empty_dict)) # <class 'dict'>
# ✅ Use set() for empty sets
empty_set = set()
print(type(empty_set)) # <class 'set'>
print(len(empty_set)) # 0
print(bool(empty_set)) # False (empty = falsy)
Set Properties
Unordered
Sets have no index — you cannot access elements by position:
s = {3, 1, 2}
# print(s[0]) # TypeError: 'set' object is not subscriptable
Unique
Every element appears at most once:
s = {1, 1, 2, 2, 3, 3}
print(s) # {1, 2, 3}
print(len(s)) # 3
Mutable
You can add and remove elements:
s = {1, 2, 3}
s.add(4)
s.remove(1)
print(s) # {2, 3, 4}
Hashable Elements Requirement
Set elements must be hashable (immutable):
# ✅ Valid elements
s = {1, 2.5, "hello", (1, 2), True, None}
# ❌ Invalid — mutable types
# s = {[1, 2]} # TypeError: unhashable type: 'list'
# s = {{"a": 1}} # TypeError: unhashable type: 'dict'
# s = {{1, 2}} # TypeError: unhashable type: 'set'
Deduplicating a List
One of the most common uses for sets:
names = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Diana"]
unique = list(set(names))
print(unique) # ['Diana', 'Charlie', 'Alice', 'Bob'] — order not preserved
To preserve order:
names = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Diana"]
unique = list(dict.fromkeys(names))
print(unique) # ['Alice', 'Bob', 'Charlie', 'Diana'] — order preserved
Membership Testing (Why Sets Are Fast)
# Set lookup is O(1) — constant time
large_set = set(range(1_000_000))
print(999_999 in large_set) # True (instant)
# List lookup is O(n) — linear time
large_list = list(range(1_000_000))
print(999_999 in large_list) # True (much slower for large lists)
Summary
- Create with
{1, 2, 3}orset(iterable) - Empty set:
set()(not{}) - Unordered, unique, mutable
- Elements must be hashable (immutable types)
- Duplicate values are automatically removed
- O(1) membership testing — much faster than lists
Next up: Set Operations →