Skip to main content
Practice

Accessing Specific Elements with Tuple Indexing

Like lists, tuples allow you to access the value of elements at specific positions using indexing.

The index of a tuple starts from 0.


Accessing Elements by Index

To access a specific element in a tuple, you use square brackets [] with the index number.

For example, to access the third element of a tuple, use the index 2 like my_tuple[2].

Tuple Indexing Example
my_tuple = ('apple', 'banana', 'cherry')

# Access the first element
first_element = my_tuple[0]
# Outputs apple
print("first_element:", first_element)

# Access the third element
third_element = my_tuple[2]
# Outputs cherry
print("third_element:", third_element)

Negative Indexing

You can access elements from the end of a tuple using negative indices.

-1 refers to the last element, and -2 refers to the second-to-last element.

Negative Indexing Example
my_tuple = ('apple', 'banana', 'cherry')

# Access the last element
last_element = my_tuple[-1]
# Outputs cherry
print("last_element:", last_element)


# Access the second-to-last element
second_last = my_tuple[-2]
# Outputs banana
print("second_last:", second_last)

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.