How to Access Tuple Items in Python
Learn how to access elements in a Python tuple by referring to their index. Understand the correct usage of square brackets to retrieve specific items from a tuple based on their position.
Access Tuple Items
You can access items in a tuple by referring to the index number, inside square brackets:
Example
thistuple = ("grape", "orange", "mango")
print(thistuple[1])
Output
orange
Note: The first item has index 0.
Negative Indexing
Negative indexing means starting from the end of the tuple. For example, -1 refers to the last item, -2 refers to the second last item, and so on.
Example
thistuple = ("grape", "orange", "mango")
print(thistuple[-1])
Output
mango
Range of Indexes
You can specify a range of indexes by indicating where to start and where to end the range. When specifying a range, the return value will be a new tuple with the specified items.
Example
thistuple = ("grape", "orange", "mango", "apple", "banana", "kiwi", "melon")
print(thistuple[2:5])
Output
('mango', 'apple', 'banana')
Note: The search will start at index 2 (included) and end at index 5 (not included). Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
thistuple = ("grape", "orange", "mango", "apple", "banana", "kiwi", "melon")
print(thistuple[:4])
Output
('grape', 'orange', 'mango', 'apple')
By leaving out the end value, the range will go on to the end of the tuple:
Example
thistuple = ("grape", "orange", "mango", "apple", "banana", "kiwi", "melon")
print(thistuple[2:])
Output
('mango', 'apple', 'banana', 'kiwi', 'melon')
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the tuple:
Example
thistuple = ("grape", "orange", "mango", "apple", "banana", "kiwi", "melon")
print(thistuple[-4:-1])
Output
('apple', 'banana', 'kiwi')
Check if Item Exists
To determine if a specified item is present in a tuple, use the in
keyword:
Example
thistuple = ("grape", "orange", "mango")
if "orange" in thistuple:
print("Yes, 'orange' is in the fruits tuple")
Output
Yes, 'orange' is in the fruits tuple