0% completed
Since tuples are ordered sequences, elements can be accessed using indexing, just like lists. Python provides two types of indexing to retrieve tuple elements:
0
for the first element, 1
for the second, and so on.-1
for the last element, -2
for the second-last, and so forth.Tuples also support slicing, which allows extracting a portion of the tuple rather than just a single element.
Positive indexing starts counting from 0
, which represents the first element of the tuple.
my_tuple[0]
retrieves the first element (10
).my_tuple[2]
retrieves the third element (30
).my_tuple[4]
retrieves the last element using its positive index (50
).Negative indexing allows accessing elements from the end of the tuple, where -1
represents the last element. This is useful when working with unknown-length tuples, allowing access without needing to calculate the exact index.
my_tuple[-1]
retrieves the last element (50
).my_tuple[-2]
retrieves the second-last element (40
).my_tuple[-3]
retrieves the third-last element (30
).Negative indexing is particularly useful when working with large tuples where counting from the end is easier than from the beginning.
Tuples allow accessing elements using positive and negative indexing. These techniques ensure efficient retrieval of tuple elements, making data handling more convenient in Python.
.....
.....
.....