Membership testing
Checking whether a value belongs to a collection efficiently and directly.
Python · Class
set creates a mutable, unordered collection of distinct hashable objects. It supports membership, iteration, deduplication, and set operations.
The set class builds a mutable collection of distinct hashable elements from an optional iterable. Sets support membership tests, iteration, length checks, and mathematical operations, but they do not preserve positional order or support indexing.
class set(iterable=(), /)| Name | Type | Description |
|---|---|---|
iterable | iterable | Optional iterable whose elements become the new set's members; omitting it creates an empty set. |
A new mutable set containing the distinct hashable elements taken from iterable; without an iterable, an empty set.
tags = {"python", "backend", "python"}
tags.add("scripting")
print("python" in tags)
print(sorted(tags))
print(tags & {"python", "web"})Creates a set that removes a duplicate, adds an element, tests membership, and computes an intersection.
Checking whether a value belongs to a collection efficiently and directly.
Converting an iterable into unique values.
Comparing or combining collections with union, intersection, difference, or symmetric difference.
set(iterable) returns a new mutable set containing the iterable's distinct hashable elements. Calling set() without an iterable creates an empty set.
Follow-up: How would you represent a set as a dictionary key? Use frozenset, whose contents cannot be changed and which is hashable.
A set stores distinct elements without positional order. It supports membership testing, length, iteration, and operations such as union, intersection, difference, and symmetric difference.
Follow-up: Why is a set useful for deduplication? Constructing it from an iterable retains one occurrence of each distinct hashable value.
The set type is mutable, so methods such as add() and remove() can change its contents. Because it is unordered, it does not support indexing or slicing.
Follow-up: What should code use instead of positional access? Iterate over the set or use a separate ordered collection when order matters.
frozensetset comprehensionadd()remove()unionintersectiondifferencesymmetric difference