Access Tuple Elements in Python
Table of Content:
We can access the objects of a tuple in a variety of ways.
Indexing
To access an object of a tuple, we can use the index operator [], where indexing in the tuple starts from 0.
A tuple with 5 items will have indices ranging from 0 to 4. An IndexError will be raised if we try to access an index from the tuple that is outside the range of the tuple index. In this case, an index above 4 will be out of range.
We cannot give an index of a floating data type or other kinds because the index in Python must be an integer. TypeError will appear as a result if we give a floating index.
The example below illustrates how indexing is performed in nested tuples to access elements.
Example
# Python program to show how to access tuple elements # Creating a tuple tuple_ = ("Python", "Tuple", "Ordered", "Collection") print(tuple_[0]) print(tuple_[1]) # trying to access element index more than the length of a tuple try: print(tuple_[5]) except Exception as e: print(e) # trying to access elements through the index of floating data type try: print(tuple_[1.0]) except Exception as e: print(e) # Creating a nested tuple nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7)) # Accessing the index of a nested tuple print(nested_tuple[0][3]) print(nested_tuple[1][1])
Output
Python Tuple tuple index out of range tuple indices must be integers or slices, not float l 6
Negative Indexing
Python's sequence objects support negative indexing.
The last item of the collection is represented by -1, the second last item by -2, and so on.
Example
# Python program to show how negative indexing works in Python tuples # Creating a tuple tuple_ = ("Python", "Tuple", "Ordered", "Collection") # Printing elements using negative indices print("Element at -1 index: ", tuple_[-1]) print("Elements between -4 and -1 are: ", tuple_[-4:-1])
Output
Element at -1 index: Collection Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')
Slicing
We can use a slicing operator, a colon (:), to access a range of tuple elements.
Example
# Python program to show how slicing works in Python tuples # Creating a tuple tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects") # Using slicing to access elements of the tuple print("Elements between indices 1 and 3: ", tuple_[1:3]) # Using negative indexing in slicing print("Elements between indices 0 and -4: ", tuple_[:-4]) # Printing the entire tuple by using the default start and end values. print("Entire tuple: ", tuple_[:])
Output
Elements between indices 1 and 3: ('Tuple', 'Ordered') Elements between indices 0 and -4: ('Python', 'Tuple') Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')