Python From Beginner to Advanced

0% completed

Previous
Next
Python - Accessing Tuple Elements

Since tuples are ordered sequences, elements can be accessed using indexing, just like lists. Python provides two types of indexing to retrieve tuple elements:

  1. Positive Indexing – Starts from 0 for the first element, 1 for the second, and so on.
  2. Negative Indexing – Starts from -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.

1. Accessing Elements Using Positive Indexing

Positive indexing starts counting from 0, which represents the first element of the tuple.

Example 1: Accessing Elements Using Positive Indexing

Python3
Python3

. . . .

Explanation

  • 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).

2. Accessing Elements Using Negative Indexing

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.

Example 2: Accessing Elements Using Negative Indexing

Python3
Python3

. . . .

Explanation

  • 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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next