Access Tuple Items
To read a tuple item, put its index number inside square brackets:
Example
Index 1 gives us the second item:
Output: complete Python program
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Negative Indexing
A negative index counts backward from the end of the tuple.
So -1 is the final item, -2 is the one just before it, and so on.
Example
Get the final item and print it:
Output: complete Python program
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Range of Indexes
To get several items at once, give a start and an end for the range.
The result comes back as a new tuple holding just those items.
Example
Get the items in third, fourth and fifth position:
Output: complete Python program
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
Example
Leave out the start and the range begins at the first item, stopping just before "kiwi":
Output: complete Python program
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
Example
Leave out the end and the range runs from "cherry" through the last item:
Output: complete Python program
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])
Range of Negative Indexes
A range can also use negative indexes, which count back from the end of the tuple:
Example
The range starts at index -4, which is included, and stops at index -1, which is left out:
Output: complete Python program
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
Check if Item Exists
The in keyword tells you whether a given item is in a tuple:
Example
Test whether the tuple contains "apple":
Output: complete Python program
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")