Table of Contents
ToggleTuples in Python are immutable, ordered collections of elements. This guide explains how to access tuple items using indexing, negative indexing, slicing, and extracting subtuples.
Each element in a tuple corresponds to an index, starting from 0. You can access tuple elements using their index.
tuple1 = ("Rohan", "Physics", 21, 69.75)
tuple2 = (1, 2, 3, 4, 5)
print("Item at 0th index in tuple1:", tuple1[0]) # Output: Rohan
print("Item at index 2 in tuple2:", tuple2[2]) # Output: 3
Negative indexing allows you to access elements from the end of the tuple. The index -1 refers to the last element, -2 to the second last, and so on.
tup1 = ("a", "b", "c", "d")
tup2 = (25.50, True, -55, 1+2j)
print("Item at -1 index in tup1:", tup1[-1]) # Output: d
print("Item at -3 index in tup2:", tup2[-3]) # Output: True
You can access a range of tuple items using slicing with negative indices.
tup1 = ("a", "b", "c", "d")
tup2 = (1, 2, 3, 4, 5)
print("Items from index 1 to last in tup1:", tup1[1:]) # Output: ('b', 'c', 'd')
print("Items from index 2 to last in tup2:", tup2[2:-1]) # Output: (3, 4)
The slice operator [start:stop] is used to fetch a range of elements from a tuple. The start index is inclusive, and the stop index is exclusive.
tuple1 = ("a", "b", "c", "d")
tuple2 = (25.50, True, -55, 1+2j)
tuple3 = (1, 2, 3, 4, 5)
print("Items from index 1 to last in tuple1:", tuple1[1:]) # Output: ('b', 'c', 'd')
print("Items from index 0 to 1 in tuple2:", tuple2[:2]) # Output: (25.5, True)
print("All items in tuple3:", tuple3[:]) # Output: (1, 2, 3, 4, 5)
A subtuple is a consecutive sequence of elements from the original tuple. You can extract a subtuple using the slice operator with appropriate start and stop indices.
tuple1 = ("a", "b", "c", "d")
tuple2 = (25.50, True, -55, 1+2j)
print("Items from index 1 to 2 in tuple1:", tuple1[1:3]) # Output: ('b', 'c')
print("Items from index 0 to 1 in tuple2:", tuple2[0:2]) # Output: (25.5, True)
Enroll in our Python certification course at Vista Academy and become a certified expert to boost your career.
Enroll Now