Python tuple is a collection of ordered and unchangeable items. The tuple is represented by using round brackets.
In this article, I have shared some useful methods to traverse the items of the Python tuple. There are various methods to find elements of the tuple. It is easy to get the first element of the tuple if the tuple has no sublists or tuples.
Using Tuple Index
The elements of the Python tuple can be easily accessed by using their unique index value.
Example
languages = ('java', 'python', 'c++', 'ruby', 'javascript')
first_element = languages[0]
print(first_element)
Output
java
Get an Element from the Tuple of Tuples
Sometimes, a Python tuple element itself acts as a tuple. In such case, we need to identify the right index of the tuple of the main Tuple in order to get the element of the child Tuple. Here is an example to understand the concept better.
Example
In the below example, the tuple contains three elements. In which, the first two elements are tuples and the last element is a string.
First, we get the first element of the main tuple and store it in a variable. Then, we find the first element of the child tuple using the index of the tuple.
languages = (('java', 'python'), ('c++', 'ruby'), 'javascript')
first_tuple = languages[0]
first_element = first_tuple[0]
print(f'first element of main tuple => {first_tuple}')
print(f'first element of first tuple => {first_element}')
Output
first element of main tuple => ('java', 'python')
first element of first tuple => java