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]) # EarthNegative 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]) # EarthSlicing 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)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)