set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices
The built-in set() function creates a mutable, unordered collection of unique hashable elements — the go-to data structure for membership testing, deduplication, mathematical set operations (union, intersection, difference), and fast lookups. In 2026 it remains one of the most powerful and frequently used built-ins for data cleaning, filtering duplicates, caching, configuration sets, and algorithm implementation (graph traversal, unique items, etc.).
With Python 3.12–3.14+ delivering faster set operations, improved free-threading safety for concurrent set modifications (with locks when needed), and better type hinting (generics support), set() is more efficient and type-safe than ever. This March 24, 2026 update covers how set() works today, real-world patterns, performance notes, and best practices for readable, performant, and concurrent set usage in modern Python.
TL;DR — Key Takeaways 2026
set(iterable)→ creates mutable set of unique items- 2026 best practice: Prefer set comprehensions for filtering; set() for conversion/deduplication
- Main use cases: remove duplicates, membership testing (O(1)), set operations, caching keys
- Type-safe pattern:
set[T]from typing with generics - Performance: O(1) average lookup/insert/delete — highly optimized
1. Basic Usage — Creating & Using Sets
# Empty set (note: {} is dict!)
empty = set()
# From iterable (deduplicates automatically)
s1 = set([1, 2, 2, 3])
print(s1) # {1, 2, 3}
# From string
s2 = set("hello")
print(s2) # {'h', 'e', 'l', 'o'} (order may vary)
# Adding / removing
s1.add(4)
s1.remove(2)
print(s1) # {1, 3, 4}
2. Real-World Patterns in 2026
Deduplication & Unique Items
from typing import Any
def unique_items(items: list[Any]) -> list[Any]:
return list(dict.fromkeys(items)) # sets are unordered; dict keys keep first-seen order
raw = [1, 2, 2, "a", "a", 3]
print(unique_items(raw)) # [1, 2, 'a', 3]
Membership Testing & Filtering (FastAPI / Config)
ALLOWED_ROLES = {"admin", "editor", "viewer"}
def has_permission(user_roles: set[str]) -> bool:
return bool(user_roles & ALLOWED_ROLES) # intersection
print(has_permission({"guest", "editor"})) # True
Set Operations in Data Pipelines
def common_features(batch1: list[str], batch2: list[str]) -> set[str]:
return set(batch1) & set(batch2) # intersection
batch_a = ["feature_x", "feature_y", "feature_z"]
batch_b = ["feature_y", "feature_w"]
print(common_features(batch_a, batch_b)) # {'feature_y'}
3. set() vs frozenset() & Other Types – Comparison 2026
| Type | Mutable? | Hashable? | Best For |
|---|---|---|---|
| set() | Yes | No | Mutable, changing collections |
| frozenset() | No | Yes | Immutable, hashable sets (dict keys) |
| list() | Yes | No | Ordered sequences |
| dict.keys() / dict.values() | No (view) | No | Dictionary views |
4. Best Practices & Performance in 2026
- Prefer set comprehensions for filtering —
{x for x in iterable if cond} - Use set() for conversion — list → set, tuple → set, deduplication
- Type hints 2026:
from typing import Hashable, Iterable, Set, TypeVar T = TypeVar("T", bound=Hashable) def unique_items(it: Iterable[T]) -> Set[T]: return set(it) - Performance: set creation O(n), lookup/insert/delete O(1) average
- Free-threading (3.14+): Sets are thread-safe for reads; use locks for concurrent writes
How Sets Achieve Fast Lookups
A set stores items in a hash table, like dictionary keys. Checking x in s computes the hash of x and looks in one place, so it takes roughly the same time for ten items or ten million. The price is that items must be hashable (strings, numbers, tuples of hashable items) and that sets have no order and no duplicates. An empty set is written set(), because {} creates an empty dictionary.
Worked Example: Comparing Two Lists of Users
Set operations answer "who is new, who left, who stayed" in one line each.
last_month = {"ali", "sara", "omar"}
this_month = {"sara", "omar", "zain"}
print(sorted(this_month - last_month)) # ['zain'] new
print(sorted(last_month - this_month)) # ['ali'] left
print(sorted(this_month & last_month)) # ['omar', 'sara'] stayed
print(len(this_month | last_month)) # 4 total unique
print(type({}), type(set())) # <class 'dict'> <class 'set'>
Sorting the results only makes the printed output stable; the sets themselves are unordered.
Common Mistakes
- Using
{}for an empty set: it creates a dict - Adding lists: lists are unhashable; convert to tuples
- Relying on order: sort when order matters
Quick Summary
- Sets give fast membership tests
- Use
-,&,|for comparisons - Items must be hashable
Conclusion — set() in 2026: Unordered Unique Collection Essential
set() is Python’s fastest and most natural way to handle unique items, membership testing, and set operations. In 2026, use it for deduplication, fast lookups, configuration sets, caching, and data pipelines; prefer frozenset when immutability/hashability is required. It’s performant, memory-efficient, and one of Python’s most powerful built-ins for efficient, readable code.
Next steps:
- Replace any duplicate removal loop with set() conversion