Tuples & Sets
Checking access...
Tuples
Tuples are immutable sequences — once created, they cannot be changed.
# Creating tuplesempty = ()single = (42,) # Note the trailing comma!coordinates = (10, 20)mixed = (1, "hello", 3.14)
# Parentheses are optional in many contextspoint = 10, 20print(type(point)) # <class 'tuple'>
# From other iterablestuple([1, 2, 3]) # (1, 2, 3)tuple("abc") # ('a', 'b', 'c')Tuple Operations
point = (3, 4)
# Indexing and slicing — same as listspoint[0] # 3point[-1] # 4
# point[0] = 5 # TypeError! Tuples are immutable
# Concatenation and repetition(1, 2) + (3, 4) # (1, 2, 3, 4)(1,) * 3 # (1, 1, 1)
# Membership3 in (1, 2, 3) # True
# Unpackingx, y = (10, 20) # x=10, y=20x, y = y, x # Swap — works because tuple on RHSWhen to Use Tuples
# Fixed data that shouldn't changeDAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
# Function returning multiple valuesdef min_max(items): return min(items), max(items)
low, high = min_max([3, 1, 4, 1, 5])print(low, high) # 1 5
# Dictionary keys (lists can't be keys)locations = { (40.7128, -74.0060): "New York", (51.5074, -0.1278): "London",}
# Named tuples for lightweight objectsfrom collections import namedtuplePoint = namedtuple("Point", ["x", "y"])p = Point(3, 4)print(p.x, p.y) # 3 4print(p[0], p[1]) # 3 4 — also supports indexingSets
Sets are unordered collections of unique elements.
# Creating setsempty = set() # {} creates an empty dict, not set!numbers = {1, 2, 3, 4, 5}mixed = {1, "hello", 3.14}
# From other iterables — duplicates are removedset([1, 2, 2, 3, 3, 3]) # {1, 2, 3}set("mississippi") # {'m', 'i', 's', 'p'}Set Operations
a = {1, 2, 3, 4}b = {3, 4, 5, 6}
# Uniona | b # {1, 2, 3, 4, 5, 6}a.union(b)
# Intersectiona & b # {3, 4}a.intersection(b)
# Differencea - b # {1, 2} — in a but not bb - a # {5, 6} — in b but not a
# Symmetric differencea ^ b # {1, 2, 5, 6} — in either but not both
# Subset/superset{1, 2}.issubset(a) # Truea.issuperset({1, 2}) # TrueSet Methods
items = {1, 2, 3}
# Adding and removingitems.add(4) # {1, 2, 3, 4}items.add(2) # No effect — 2 already existsitems.remove(3) # Removes 3 — KeyError if not founditems.discard(10) # Removes if exists, no error if notpopped = items.pop() # Removes and returns arbitrary elementitems.clear() # Empty the set
# Set comprehensionssquares = {x ** 2 for x in range(10)}# {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}Frozenset
An immutable version of set:
fs = frozenset([1, 2, 3])# fs.add(4) # AttributeError!# Can be used as dictionary keydata = {frozenset({1, 2}): "pair"}Performance Comparison
| Operation | List | Tuple | Set |
|---|---|---|---|
| Lookup by index | O(1) | O(1) | N/A |
| Membership check | O(n) | O(n) | O(1) |
| Add element | O(1) | N/A | O(1) |
| Delete element | O(n) | N/A | O(1) |
Sets excel at membership testing and deduplication:
# Remove duplicates from a listitems = [1, 2, 2, 3, 3, 3]unique = list(set(items)) # [1, 2, 3] — order may varyKey Takeaways
- Tuples are immutable — use for fixed data, return values, dict keys
- Tuples with one element need a trailing comma:
(42,) - Sets store unique elements — great for deduplication and membership tests
- Set operations:
|union,&intersection,-difference,^symmetric difference - Membership checks are O(1) for sets vs O(n) for lists
- Use
frozensetfor immutable, hashable sets