Skip to content

Computer Science · Ch 10 — Tuples and Dictionaries

Accessing Elements in a Tuple

10.1.1

Accessing Elements in a Tuple

Elements of a tuple are accessed exactly the way elements of a list or characters of a string are accessed — through indexing (and, as we will see later in the chapter, slicing). The first element is at index 0, the second at index 1, and so on.

Positive indexing

>>> t = (3, 6, 9, 12, 15, 18)   # a tuple of six elements

>>> t[0]        # first element
3
>>> t[3]        # fourth element (index 3)
12

Index out of range

Asking for an index that does not exist raises an IndexError:

>>> t[15]
IndexError: tuple index out of range

The index can be any expression that evaluates to an integer

You are not limited to writing a literal number inside the square brackets — any expression producing a valid integer index works:

>>> t[2 + 3]    # expression evaluates to index 5
18

Negative indexing

Like strings and lists, tuples support negative indices, which count from the right end. Index -1 is the last element, -2 the second-last, and so on: