vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns str() in Python 2026: String Conversion + Modern Formatting & Best Practices type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns super() in Python 2026: Method Resolution & Modern Inheritance Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices round() in Python 2026: Rounding Numbers + Modern Precision & Use Cases reversed() in Python 2026: Reverse Iteration + Modern Patterns & Best Practices repr() in Python 2026: Official String Representation + Modern Debugging & Serialization Use Cases pow() in Python 2026: Power & Modular Exponentiation + Modern Use Cases & Best Practices property() in Python 2026: Properties, Getters/Setters & Modern Patterns ord() in Python 2026: Unicode Code Point from Character + Modern Use Cases & Best Practices open() in Python 2026: File Handling + Modern I/O Patterns & Best Practices range() in Python 2026: Efficient Sequence Generation + Modern Patterns & Best Practices print() in Python 2026: Output Formatting + Modern CLI & Debugging Patterns View all in this category →

set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices

Built In Function Mar 24, 2026

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()YesNoMutable, changing collections
frozenset()NoYesImmutable, hashable sets (dict keys)
list()YesNoOrdered sequences
dict.keys() / dict.values()No (view)NoDictionary 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

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices