![]() |
VOOZH | about |
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.
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:
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:
Table of Content
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.
50 40
Sometimes we may want to access a range of items in a tuple, not just one. Python allows us to do this using slicing.
(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.
We may want to access all the items in a tuple. We can use a loop to go through each item:
10 20 30 40 50