Tuples and sets round out the four built-in collection types (list, tuple, set, dict). Tuples are immutable sequences — like read-only lists. Sets are unordered collections of unique elements.
Creating tuples
# Parentheses — most commonpoint = (10, 20)rgb = (255, 100, 50)# Parens are optional but recommendedpoint2 = 10, 20# Single-element tuple — comma is REQUIREDsingle = (42,) # tuplenot_a_tuple = (42) # just an int in parens# Empty tupleempty = ()# From an iterablechars = tuple("hello") # ('h', 'e', 'l', 'l', 'o')
When to use a tuple instead of a list
- The collection should not change — coordinates, RGB triples, database rows.
- You need it to be hashable — tuples can be dictionary keys; lists cannot.
- You're returning multiple values from a function — Python returns a tuple by default.
- You want a small performance edge — tuples are slightly faster to create and iterate.
def location():return 28.6139, 77.2090 # returns a tuplelat, lon = location()print(lat, lon)# Tuple as dict key — common for caching gridsdistances = {}distances[(0, 0)] = 0distances[(1, 0)] = 1.0
Tuple unpacking
# Basic unpackx, y = (10, 20)print(x, y) # 10 20# Swap variables — no temp var neededa, b = 1, 2a, b = b, aprint(a, b) # 2 1# Star unpacking — collect "the rest"first, *middle, last = [1, 2, 3, 4, 5]print(first) # 1print(middle) # [2, 3, 4]print(last) # 5# In iteration with enumeratefor i, fruit in enumerate(["apple", "mango", "kiwi"]):print(f"{i}: {fruit}")
Creating sets
Sets store unique elements with no defined order. Membership tests are O(1).
# Curly braces — most commonfruits = {"apple", "mango", "banana"}# From an iterable — duplicates are removedunique = set([1, 2, 2, 3, 3, 3, 4])# {1, 2, 3, 4}# ⚠️ Empty set — must use set(), NOT {}empty = set() # {} would create an empty DICT# Adding & removingfruits.add("kiwi")fruits.discard("apple") # no error if missingfruits.remove("mango") # KeyError if missing# Membership — fast even for huge setsprint("apple" in fruits)
Set operations
| Operation | Operator | Method |
|---|---|---|
| Union (a ∪ b) | a | b | a.union(b) |
| Intersection (a ∩ b) | a & b | a.intersection(b) |
| Difference (a - b) | a - b | a.difference(b) |
| Symmetric diff | a ^ b | a.symmetric_difference(b) |
| Subset | a <= b | a.issubset(b) |
| Superset | a >= b | a.issuperset(b) |
a = {1, 2, 3, 4}b = {3, 4, 5, 6}print(a | b) # {1, 2, 3, 4, 5, 6} unionprint(a & b) # {3, 4} intersectionprint(a - b) # {1, 2} in a but not bprint(a ^ b) # {1, 2, 5, 6} xor / symmetric diff# Practical: find users active on both platformsios_users = {"u1", "u2", "u3", "u4"}web_users = {"u3", "u4", "u5"}both = ios_users & web_users # {'u3', 'u4'}mobile_only = ios_users - web_users # {'u1', 'u2'}
frozenset
tags = frozenset(["python", "ml", "interview"])# tags.add("data") # AttributeError — immutable# Can be a dict keygroups = {frozenset(["python", "ml"]): "Data Science cohort",frozenset(["sql", "powerbi"]): "Analytics cohort"}
Key takeaways
- 01Tuples are immutable lists — use them for fixed-shape data, dict keys, and multi-value returns.
- 02A single-element tuple needs a trailing comma: (42,).
- 03Tuple unpacking (incl. star *) makes Python idiomatic — swap, destructure, iterate.
- 04Sets are unordered, unique, with O(1) membership — perfect for dedupe and overlap checks.
- 05Use set() for an empty set; {} is an empty dict.
- 06Reach for set operators (|, &, -, ^) for clean overlap/diff logic.
- 07frozenset is the immutable, hashable cousin — use as dict keys or set-of-sets.
