Python Access Tuples

You read values out of a tuple using index numbers, negative indexes, and slices.

Indexing tuple items

Every item in a tuple has a numbered position. Counting starts at zero, so the first item is at index 0, the second at index 1, and so on. You retrieve an item by writing its index inside square brackets after the tuple name.

Access by index

planets = ("Mercury", "Venus", "Earth", "Mars")
print(planets[0])   # Mercury
print(planets[2])   # Earth
Note: Asking for an index that does not exist, such as planets[10] in a four-item tuple, raises an IndexError. Always keep indexes within the valid range from 0 to len(tuple) - 1.

Negative indexing

Negative indexes count backwards from the end of the tuple. Index -1 refers to the last item, -2 to the second-to-last, and so on. This is convenient when you care about the end of the sequence and do not want to calculate its length first.

Access from the end

planets = ("Mercury", "Venus", "Earth", "Mars")
print(planets[-1])  # Mars
print(planets[-2])  # Earth

Slicing a range of items

A slice returns a new tuple containing a range of items. The syntax is tuple[start:stop], where the item at the start index is included but the item at the stop index is not. Leaving out start begins at the beginning, and leaving out stop runs to the end.

Slicing tuples

nums = (10, 20, 30, 40, 50, 60)
print(nums[1:4])    # (20, 30, 40)
print(nums[:3])     # (10, 20, 30)
print(nums[3:])     # (40, 50, 60)
print(nums[-3:])    # (40, 50, 60)
ExpressionMeaningResult for (10,20,30,40,50,60)
nums[0]First item10
nums[-1]Last item60
nums[1:4]Index 1 up to (not including) 4(20, 30, 40)
nums[:2]Start through index 1(10, 20)

Checking for a value and looping

Use the in keyword to test whether a value exists in a tuple, and a for loop to visit each item in turn. Both are common ways to work with tuple contents without needing indexes.

Membership test and looping

fruits = ("apple", "banana", "cherry")

if "banana" in fruits:
    print("Yes, banana is here")

for fruit in fruits:
    print(fruit)
Note: Slicing never changes the original tuple; it always produces a brand-new tuple. This lets you extract portions of immutable data safely.