Sub topic 3
Indexing, slicing and common operations
This chapter covers how to read values out of a tuple and which operations work on whole tuples. It assumes you can write basic Python (variables, loops, functions) and know how list indexing works. Tuples share almost all of their read-only behavior with lists, so most of this will feel familiar. The differences matter when you write code that depends on them.
Indexing
A tuple is an ordered sequence, so every item has a position. Positions start at 0 from the left. Negative positions count from the right, starting at -1.
colors = ("red", "green", "blue", "yellow", "black")
print(colors[0])
print(colors[-1])
print(colors[-2])
try:
colors[5]
except IndexError as e:
print(e)This prints red, black, yellow, and then tuple index out of range.
Each item has two valid indexes, one positive and one negative:
| Item | red | green | blue | yellow | black |
|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 |
| Negative index | -5 | -4 | -3 | -2 | -1 |
For a tuple of length n, valid indexes run from -n to n - 1. Anything outside that range raises IndexError. Indexing an empty tuple always fails, which is a common source of bugs when a function returns () for "no results" and the caller reads result[0] without checking.
Indexing returns the item itself, whatever its type. If the item is another tuple, you can chain indexes:
segment = ((0, 0), (4, 3))
print(segment[1][0])This prints 4. Chained indexes are hard to read, though. The chapters on unpacking show clearer alternatives.
Slicing
A slice has the form t[start:stop:step]. It returns a new tuple. The start index is included and the stop index is excluded. Any of the three parts can be left out.
colors = ("red", "green", "blue", "yellow", "black")
print(colors[1:3])
print(colors[:2])
print(colors[3:])
print(colors[::2])
print(colors[::-1])
print(colors[10:20])
print(colors[1:2])
print(colors[1])The output is:
('green', 'blue')
('red', 'green')
('yellow', 'black')
('red', 'blue', 'black')
('black', 'yellow', 'blue', 'green', 'red')
()
('green',)
greenFour points in this output are worth remembering.
- Slices never raise
IndexError. Out-of-range bounds are clamped, socolors[10:20]gives an empty tuple. Single-item indexing is strict and slicing is forgiving. - A slice is always a tuple.
colors[1:2]is('green',), a tuple with one item, whilecolors[1]is the string'green'. Mixing these up is a frequent mistake. - A negative step walks backward.
colors[::-1]is the usual way to reverse a tuple. In that case,startandstopalso swap roles, socolors[3:0:-1]gives('yellow', 'blue', 'green'). - The result is a new tuple. Slicing never changes the original. The new tuple holds references to the same item objects, so slicing does not copy the items themselves.
A step of 0 is an error. colors[::0] raises ValueError: slice step cannot be zero.
Slice objects
A slice can be stored in a variable with slice() and reused. This helps when you apply the same layout to many tuples, such as fixed-position fields in records.
NAME_AND_AGE = slice(0, 2)
rows = [
("Ada", 36, "London", "UK"),
("Linus", 54, "Helsinki", "FI"),
]
for row in rows:
print(row[NAME_AND_AGE])This prints ('Ada', 36) and then ('Linus', 54).
Common operations
Tuples support every read-only sequence operation that lists do. The table gives a quick overview, and the sections below show the details.
| Operation | Meaning | Example result |
|---|---|---|
| `len(t)` | Number of items | `3` |
| `x in t` | Membership test | `True` |
| `t + u` | Concatenation into a new tuple | `(1, 2, 3, 4, 5)` |
| `t * n` | Repetition into a new tuple | `(1, 2, 3, 1, 2, 3)` |
| `t.count(x)` | How many items equal `x` | `2` |
| `t.index(x)` | Position of the first `x` | `2` |
| `min(t)`, `max(t)`, `sum(t)` | Aggregates over the items | `1`, `9`, `31` |
| `sorted(t)` | A sorted **list** | `[1, 1, 2, 3, 4, 5, 6, 9]` |
Length, membership, concatenation and repetition
a = (1, 2, 3)
b = (4, 5)
print(len(a))
print(2 in a)
print(9 not in a)
print(a + b)
print(a * 2)This prints 3, True, True, (1, 2, 3, 4, 5) and (1, 2, 3, 1, 2, 3).
The + operator needs a tuple on both sides. (1, 2) + [3] raises TypeError, because Python will not guess whether you want a tuple or a list. Convert one side first, for example (1, 2) + tuple([3]).
Searching with count and index
Tuples have exactly two methods, count and index. They have no append, sort or remove, because those would change the tuple.
nums = (3, 1, 4, 1, 5, 9, 2, 6)
print(nums.count(1))
print(nums.index(4))
print(nums.index(1, 2))
try:
nums.index(7)
except ValueError:
print("not found")
print(min(nums), max(nums), sum(nums))
print(sorted(nums))
print(tuple(sorted(nums)))The output is:
2
2
3
not found
1 9 31
[1, 1, 2, 3, 4, 5, 6, 9]
(1, 1, 2, 3, 4, 5, 6, 9)index returns the first match only. A second argument gives the position to start searching from, which is how nums.index(1, 2) finds the second 1 at position 3. If the value is absent, index raises ValueError. It does not return -1 the way some other languages do. Guard with in first, or catch the exception.
sorted() always returns a list, even for a tuple input. Wrap it in tuple(...) when you need a tuple back. reversed(t) similarly returns an iterator, not a tuple, so use t[::-1] when you want a tuple.
Comparison
Tuples compare item by item from the left, stopping at the first difference. If one tuple is a prefix of the other, the shorter one is smaller.
print((1, 2) < (1, 3))
print((1, 2, 3) < (1, 3))
print((2,) > (1, 99, 99))
print(("a", 1) == ("a", 1))
print((1, 2) < (1, 2, 0))All five lines print True. This ordering is called lexicographic ordering. It is why sorting a list of tuples works without any extra code, since sorted orders by the first item, then by the second to break ties, and so on.
people = [("Grace", 91), ("Ada", 95), ("Grace", 88)]
print(sorted(people))This prints [('Ada', 95), ('Grace', 88), ('Grace', 91)].
Comparison fails if two items at the same position cannot be compared. (1, "a") < (1, 2) raises TypeError, because Python reaches the second items and cannot order a string against an integer.
Edge cases and gotchas
Repetition copies references, not objects
t * n repeats the same item objects. With immutable items this is harmless. With mutable items it creates aliases.
rows = ([],) * 2
rows[0].append(1)
print(rows)
print(rows[0] is rows[1])This prints ([1], [1]) and then True. Both positions hold the same list, so appending through one shows up in both. If you need independent lists, build them separately, for example with tuple([] for _ in range(2)).
Augmented assignment rebinds the name
Writing t += (3,) on a tuple does not change the tuple. It builds a new one and points the name at it.
t = (1, 2)
old = t
t += (3,)
print(t)
print(old)
print(t is old)This prints (1, 2, 3), (1, 2) and False. A second name that referred to the old tuple still sees the old value. This is the behavior you want from an immutable type, but it surprises people who expect += to work like list.extend.
Because each concatenation copies every item, building a tuple in a loop with += takes quadratic time overall. Collect the items in a list and convert once at the end with tuple(items).
Assignment and deletion are errors
Item assignment, item deletion and slice assignment all raise TypeError, and mutating methods do not exist.
t = (1, 2, 3)
for action in (lambda: t.__setitem__(0, 9), lambda: t.__delitem__(0)):
try:
action()
except TypeError as e:
print(e)
print(hasattr(t, "append"))This prints two TypeError messages, and then False. To get a "changed" tuple, build a new one from slices: t[:1] + (9,) + t[2:] gives (1, 9, 3).
Slicing does not validate length
Because slices clamp their bounds, t[:3] on a two-item tuple silently returns two items. If your code requires exactly three, check len(t) or use unpacking, which fails loudly when the length is wrong. Unpacking is covered in a later chapter.
Exercise
Given data = (10, 20, 30, 40, 50, 60), write one expression for each of these results: (a) the last two items as a tuple, (b) every second item starting with the first, (c) the tuple reversed, (d) a new tuple with 30 replaced by 99.
Show answer
(a) data[-2:] gives (50, 60). (b) data[::2] gives (10, 30, 50). (c) data[::-1] gives (60, 50, 40, 30, 20, 10). (d) data[:2] + (99,) + data[3:] gives (10, 20, 99, 40, 50, 60). The original data is unchanged in every case, because each expression builds a new tuple.
Exercise
What does this code print, and why? t = ([], []) u = t * 2 u[0].append("x") print(len(u), u[1])
Show answer
It prints 4 ['x']. Repetition creates a tuple of four items, but they are only two distinct list objects, each referenced twice. Items 0 and 2 are the first list and items 1 and 3 are the second. So u[0].append("x") changes the first list, and u[1] is the second list, which is still empty. The printed result is therefore 4 [], not 4 ['x'].