Python Access Tuple
Python Access Tuple
You can access items of a tuple using index just like a list. Provide an index in square brackets next to the reference to the tuple, and it returns the item in tuple present at the index.
The syntax to read an item present at index in tuple is
item = tuple[index]
In this tutorial we will learn how to access tuple using index, and something called negative indexing, and how to handle some of the issues while accessing the elements of a tuple.
Examples
1. Access Tuple items using index
In the following program, we will read the second item of tuple. Index of first element is zero, and the index of second element is one. So, we shall provide an index of 1 and read the item of tuple.
Python Program
vowels = ('a', 'e', 'i', 'o', 'u')
item = vowels[1]
print(item)
Output
e
2. Access Tuple items using negative index
In this example, we will use negative indexing to access the items of tuple.
Negative indexing starts with -1 at the end of tuple and decrements by from right to left.
The following picture depicts negative indexing for a tuple.
Python Program
vowels = ('a', 'e', 'i', 'o', 'u')
item = vowels[-1]
print(item) #u
item = vowels[-2]
print(item) #o
item = vowels[-3]
print(item) #i
Output
u
o
i
3. Index Out of Range when accessing items in Tuple
If you try to access an item from tuple with an index that is out of range for the tuple, you will get "IndexError: tuple index out of range" error and execution will stop.
In the following example, we have a tuple with five items. But, we will try to access item at index 8. Let us see what output do we get.
Python Program
vowels = ('a', 'e', 'i', 'o', 'u')
item = vowels[8]
print(item)
Output
Traceback (most recent call last):
File "d:/workspace/example.py", line 2, in <module>
item = vowels[8]
IndexError: tuple index out of range
We get an IndexError and the execution comes to halt.
Summary
In this tutorial of Python Examples, we learned how to access tuple items using positive index, negative index, and the error we could face if we try to access items with an index out of range.