Open In App

Python Access Tuple Item

Last Updated : 06 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, a tuple is a collection of ordered, immutable elements. Accessing the items in a tuple is easy and in this article, we'll explore how to access tuple elements in python using different methods.

Access Tuple Items by Index

Just like lists, tuples are indexed in Python. The indexing starts from 0 for the first item, 1 for the second and so on. Let’s look at a basic example:

Python
tup = (10, 20, 30, 40, 50)

# Access the first item
print(tup[0])  

Output
10


In the example above, tup[0] gives us the first item in the tuple, which is 10.

Let's explore other methods to access tuple items:

Accessing Tuple Items Using Negative Indexing

Python also supports negative indexing. This means that instead of starting from the beginning of the tuple, we can start from the end. The last item is indexed as -1, the second-to-last as -2 and so on.

Python
tup = (10, 20, 30, 40, 50)

# Access the last item
print(tup[-1])  

# Access the second-to-last item
print(tup[-2])  

Output
50
40

Accessing Range of Items Using Slicing a Tuple

Sometimes we may want to access a range of items in a tuple, not just one. Python allows us to do this using slicing.

Python
tup = (10, 20, 30, 40, 50)

# Get items from index 1 to 3 (not including 3)
print(tup[1:3])  # Output: (20, 30)

Output
(20, 30)

In the example above, we sliced the tuple starting from index 1 and ending at index 3 but since the end index is excluded, it returns the items at index 1 and 2.

Using Loop to Access All Items

We may want to access all the items in a tuple. We can use a loop to go through each item:

Python
tup = (10, 20, 30, 40, 50)

# Loop through tuple and print each item
for i in tup:
    print(i)

Output
10
20
30
40
50

Next Article

Similar Reads