The one-element tuple trap. Immutability with mutable contents. Tuple as dict keys. Packing and unpacking. These are Python-only concepts with deep gotchas.
(1) is NOT a tuple — it's just the integer 1 in parentheses. A one-element tuple requires a trailing comma: (1,). This trips up almost every Python beginner.a = (1) b = (1,) c = 1, print(type(a), type(b), type(c)) print(a, b, c)
(1) is just 1. (1,) is a one-element tuple. 1, is also a one-element tuple — parentheses are optional. This is one of Python's most surprising design decisions.t = () print(type(t)) print(len(t))
() is a valid empty tuple. Unlike the one-element case, () unambiguously means empty tuple — no comma needed. len(()) is 0. Empty tuples are used as default immutable empty sequences.t = (1, 2, 3) t[0] = 10
TypeError: 'tuple' object does not support item assignment. This immutability makes tuples hashable (when their contents are also hashable), so they can be used as dictionary keys.t = (1, [2, 3], 4) t[1].append(99) # mutate the list INSIDE the tuple print(t)
t = (1, [2, 3]) d = {t: "value"}
TypeError: unhashable type: 'list'. Tuples containing only immutable objects (ints, strings, other tuples) are hashable and can be used as keys.a, b, c = (1, 2, 3) print(a, b, c) x, *rest = (1, 2, 3, 4) print(x, rest)
*rest is the "star assignment" — it greedily captures remaining elements into a list. Note: rest becomes a list, not a tuple. You can put * in the middle too: first, *middle, last = (1,2,3,4,5).a = 1 b = 2 a, b = b, a # Python swap idiom print(a, b)
b, a on the right side creates a tuple (2, 1) first, then unpacks it into a and b. No temporary variable needed. This is the idiomatic Python swap — enabled by tuple packing/unpacking happening atomically.t = (1, 2, 3) a, b = t
ValueError: too many values to unpack (expected 2). Use a, b, _ = t to discard the third, or a, *b = t to collect extras.coords = {}
coords[(1, 2)] = "origin"
coords[(3, 4)] = "far"
print(coords[(1, 2)])
print(len(coords))
(1, 2) as a key is looked up by value equality, not identity.t = (1, 2) + (3, 4) print(t) u = (1, 2) * 3 print(u)
+ concatenates tuples (creates a new tuple). * repeats a tuple. Both operations return new tuples — the originals are unchanged (tuples are immutable). Same behavior as with lists, but the result is always a tuple.t = (3, 1, 4, 1, 5) print(sorted(t)) print(type(sorted(t)))
sorted() always returns a list, regardless of input type. If you need a sorted tuple, wrap it: tuple(sorted(t)). Tuples have no .sort() method (that would require in-place modification, violating immutability).t = (1, 2, 2, 3) print(t.count(2)) print(t.index(2)) print(2 in t)
.count(x) (count occurrences) and .index(x) (index of first occurrence). Compare this to lists which have many more. in works as a membership test. Tuples are intentionally minimal.from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(3, 4) print(p.x, p.y) print(p[0], p[1]) print(isinstance(p, tuple))
namedtuple creates a tuple subclass with named fields. You can access elements by name (p.x) or by index (p[0]). It's a proper tuple subclass — isinstance(p, tuple) is True. Great for structured data without the overhead of a full class.t = (1, 2, 3) t += (4,) print(t)
t += (4,) creates a NEW tuple (1,2,3,4) and rebinds the name t to it. The original tuple (1,2,3) is unchanged. This is the key distinction: the tuple object is immutable, but the variable can be rebound to a different tuple.pairs = [(3, "c"), (1, "a"), (2, "b")] print(sorted(pairs)) print(sorted(pairs, key=lambda x: x[1]))
sorted(pairs) sorts by first element (1, 2, 3). The second sort is by the second element ('a', 'b', 'c'). Both happen to give the same result here.