Tuples & Sets in Python

From the Python cheat sheet · Data Structures · verified Jul 2026

Tuples & Sets

Immutable sequences and unique unordered collections.

python
# Tuples — immutable, ordered
coords = (10, 20)
x, y = coords          # Unpack
single = (42,)          # Single-element tuple needs comma

# Sets — unique, unordered
s = {1, 2, 3}
s.add(4)
s.discard(2)
a & b   # intersection
a | b   # union
a - b   # difference
💡 Use tuples for fixed collections — they're faster and hashable (can be dict keys)
⚡ Create an empty set with set(), not {} — braces create an empty dict
📌 .discard() is silent on missing elements; .remove() raises KeyError
🟢 Sets are perfect for deduplication: list(set(items)) removes duplicates
tuplessetsdata-structures

More Python tasks

Back to the full Python cheat sheet