tuple.index()
Python · Tuples
Theory
.index(value) returns the position of the first item in a tuple that equals value. With colors = ('red', 'green', 'blue'), colors.index('green') is 1. Like the list version it accepts optional start and stop arguments to search only part of the tuple, and it raises ValueError (tuple.index(x): x not in tuple) if the value is missing, so check with in first or catch the error.
index() is for when you know the value and need its position. When you already know the structure of a tuple, which is the normal case for fixed records, unpacking is clearer than indexing: name, dept, salary = row gives each field a name instead of remembering row[2] is the salary. The number of names must match the number of items, otherwise Python raises ValueError; use *rest to collect extras, as in first, *rest = colors.
Why we use it
Fixed lookups, like finding where a weekday or a status sits in an ordered tuple of options, need the position of a known value. index() returns it without converting the tuple or writing a loop.
When to use it
Use index() to find the position of a known value. Use unpacking (a, b, c = t) to read the fields of a record, and a dict when you look up many values by name, since index() scans in O(n).
How it works
- Call colors.index('green')
- Start scanning at index 0 (or the given start)
- Is this item == 'green'? Yes: Return its index. No: Move to the next item.
- Reached the end with no match? Yes: Raise ValueError. No: Keep scanning.
- print shows 1
Syntax
tuple.index(value)Example
colors = ('red', 'green', 'blue')
print(colors.index('green'))Key points
- Raises a ValueError if the value isn't found
- Returns only the first matching position
- Optional start/stop limit the search: t.index(x, 1)
- Use unpacking (a, b = my_tuple) for direct positional access instead
- first, *rest = t collects the remaining items into a list