Sub topic 3
Indexing, slicing and common operations
This chapter assumes you know how to create a tuple, including the single-element comma, and that you are comfortable indexing lists. Tuples share the read-only half of the list interface, so most of this will feel familiar. The differences are in what every operation returns: a new tuple, never a change to the original.
Indexing
A tuple is ordered, so each item has a position. Positions count from 0 at the left and from -1 at the right.
t = ("a", "b", "c", "d", "e")
print(t[0]) # a
print(t[2]) # c
print(t[-1]) # e
print(t[-2]) # dAn index outside the range raises IndexError. Assigning to an index raises TypeError, because tuples do not support item assignment. The next chapter covers that limit.
Slicing
A slice has the form t[start:stop:step]. It includes start and stops before stop. Any part can be left out. A slice always returns a new tuple, even when it holds one item or none.
t = ("a", "b", "c", "d", "e")
print(t[1:3]) # ('b', 'c')
print(t[:2]) # ('a', 'b')
print(t[3:]) # ('d', 'e')
print(t[::2]) # ('a', 'c', 'e')
print(t[::-1]) # ('e', 'd', 'c', 'b', 'a')
print(t[1:2]) # ('b',)
print(t[10:]) # ()Notice the last line. A slice that goes past the end does not raise an error. It is clipped to the tuple's bounds. A single index is different, because t[10] raises IndexError.
Concatenation, repetition and membership
The operators + and * build new tuples. Neither one modifies its operands.
a = (1, 2)
b = (3,)
print(a + b) # (1, 2, 3)
print(a * 3) # (1, 2, 1, 2, 1, 2)
print(len(a + b)) # 3
print(2 in a) # True
print(9 not in a) # TrueBoth sides of + must be tuples. (1, 2) + [3] raises TypeError, and so does (1, 2) + 3. To add one item, write a + (3,) with the comma.
The two methods
A tuple has only two methods, count and index. Neither one changes the tuple, so there is no append or sort.
nums = (3, 1, 4, 1, 5)
print(nums.count(1)) # 2
print(nums.index(4)) # 2
print(nums.index(1)) # 1, the first match
try:
nums.index(9)
except ValueError:
print("not found")index returns the first match and raises ValueError when the value is absent. Check with in first if absence is a normal case.
Built-in functions and comparison
Functions such as min, max and sum accept tuples. sorted accepts one too, but it returns a list. Wrap it in tuple(...) if you need a tuple back.
nums = (3, 1, 4, 1, 5)
print(min(nums), max(nums), sum(nums)) # 1 5 14
print(sorted(nums)) # [1, 1, 3, 4, 5]
print(tuple(sorted(nums))) # (1, 1, 3, 4, 5)
print((1, 2) < (1, 3)) # True
print((1, 2, 3) < (1, 3)) # True
print((2,) > (1, 99)) # True
print((1, 2) == (1, 2)) # TrueTuples compare item by item from the left, like words in a dictionary. The first position where the items differ decides the result. If one tuple is a prefix of the other, the shorter one is smaller. This ordering is why a list of tuples sorts predictably, for example by (last_name, first_name).
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `t[len(t)]` | `IndexError` | The last index is `len(t) - 1`, or use `t[-1]` |
| `t[1:2]` expecting an item | Returns a one-item tuple | Use `t[1]` for the item itself |
| `t + (5)` | `TypeError`, because `(5)` is an int | Write `t + (5,)` |
| `t.sort()` | `AttributeError` | Use `sorted(t)` |
| `t.index(x)` on a missing value | `ValueError` | Test with `x in t` first |
Exercise
Given t = (10, 20, 30, 40, 50, 60), write one expression that returns (60, 40, 20), and say what t[4:100] returns.
Show answer
t[::-2] returns (60, 40, 20), because it starts at the end and steps back by two. t[4:100] returns (50, 60). A slice is clipped to the tuple's bounds, so an oversized stop value raises no error.
Exercise
What does (1, 2) + (3) do, and how do you fix it?
Show answer
It raises TypeError, because (3) is the integer 3 and not a tuple. Add the comma to make a one-item tuple: (1, 2) + (3,) gives (1, 2, 3).