11.5 Tuple Operators
Concatenation and repetition always build a brand-new tuple since neither can mutate, membership testing with in, and lexicographic comparison -- the same mechanism behind version-tuple comparison.
+ (Concatenation)
Combines two tuples into a new tuple — since tuples are immutable, this can never modify either original.
>>> (1, 2) + (3, 4)
(1, 2, 3, 4)
* (Repetition)
>>> (1, 2) * 3
(1, 2, 1, 2, 1, 2)
Membership (in, not in)
>>> 2 in (1, 2, 3), 5 not in (1, 2, 3)
(True, True)
Comparison Operators
Tuples compare element-by-element, lexicographically — the same rule that applies to lists and strings (see 10.6 List Operators and 9.5 String Operators), and exactly the mechanism behind version-tuple comparison like (1, 2, 0) < (1, 3, 0).
>>> (1, 2) == (1, 2)
True
>>> (1, 2) < (1, 3)
True
Quick Interview Answer
“Tuple operators mirror list operators exactly, with the one obvious difference:
+and*are the only ways to build a bigger tuple from a smaller one, since there’s no in-placeappend()orextend()to reach for instead — both always allocate a brand-new tuple. Comparison is lexicographic, element-by-element, the same rule used for strings and lists — which is also exactly what makes comparing version tuples like(1, 2, 0) < (1, 10, 0)work correctly, unlike comparing the equivalent strings'1.2.0' < '1.10.0'.”
Common Mistakes
- Reaching for
t.append(x)on a tuple out of habit — tuples have no such method;t = t + (x,)(ort = (*t, x)) is the way to “add” an element, producing a new tuple each time. - Building up a large tuple incrementally with repeated
+=in a loop — just like the equivalent list mistake, each concatenation allocates a new tuple and copies everything so far, an O(n²) pattern for n pieces. - Comparing a tuple of strings and a tuple of numbers expecting a meaningful result — mixed-type element comparison raises
TypeErrorin Python 3, the same as comparing a barestrto anintdirectly.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form