Meaning
Creates a set from an iterable, removing duplicate elements. Use when you need a collection of unique items.
Primary Function
Data structure creation
Communicative Purpose
Produces a set containing the distinct elements of the given iterable.
Pattern
set(iterable)
Core Structure
set(...)
Função primária
Data structure creation
Propósito comunicativo
Produces a set containing the distinct elements of the given iterable.
Situações de gatilho
Data cleaning: removing duplicates from a list; Algorithm design: preparing data for membership tests; Set operations: implementing union or intersection
Contextos
General Python code, data processing scripts, algorithms requiring unique collections.
Padrão
set(iterable)
Estrutura central
set(...)
Slots de substituição
iterable: any iterable (e.g., list, tuple, string)
Colocados típicos
- list comprehensions
- dict
- frozenset
- set methods like add
- remove
Substituições comuns
- set(iterable) or {*iterable} (Python 3.5+) for unpacking
- using a set literal {elem1
- elem2} when elements are known
Erros comuns
Applying set to unhashable elements (e.g., list of lists) causing TypeError; assuming order is preserved.
Similar / contraste
frozenset([iterable]) creates an immutable set; dict.fromkeys(iterable) creates a dict with keys from iterable and None values.
Interferências
Coming from languages where sets require external libraries (e.g., C++ std::set), may forget that Python's set is built‑in and unordered.
Família do chunk
- set literals
- frozenset
- dict.fromkeys
- list deduplication via set
Nuance
Sets discard duplicates and do not maintain insertion order (until Python 3.7 as an implementation detail, but not guaranteed). Not suitable when you need to retain duplicates or order.
Efeito pragmático
Guarantees uniqueness and enables O(1) membership tests, improving performance for duplicate removal and lookup.
Dica de memória
Think of a bag that automatically throws away repeats.
Nota
Removes duplicate elements and does not guarantee order (insertion order preserved as an implementation detail in CPython 3.7+ but not guaranteed). Raises TypeError if elements are unhashable (e.g., lists of lists). Useful for O(1) membership tests and set operations.
Upgrade path
Using a set comprehension {x for x in iterable} for filtering or transformation.
Log in to save chunks.