How to access items of Tuples in Python

Python

Today we are going to learn, How to access items of Tuples in Python using examples. An index starts from 0 for the first element and 1 for the second element and the last item is at n-1 for n items tuple.

We can use the positive and negative indexes to iterate on Tuple items. So let us begin with positive index access first.

1.Access tuple items by positive Index


Here in this example, we are accessing tuple elements at the 0th index and 5th index items.The tuple element at index 0 is ‘C#’ and ‘C++’ at 1 index and so on.

Program Example

langtuple = ('C#','C++','C','Java','Go','Rust')

#Accessing the tuple by index

print('first elemnt of the tuple  = \n',langtuple[0])

print('last element of tuple =\n',langtuple[5])

Output

first elemnt of the tuple  = 
 C#
last element of tuple =
  Rust

2. Access tuple items by Negative Index


We use a negative index that means starting from the end. The -1 refers to the last element -2 is the second last item and so on. The negative index can be used to iterate in reverse.

In this example, we are using the -1 index to fetch the last item. When we use the -5 index we get the second element.

Program Example

langtuple = ('C#','C++','C','Java','Go','Rust')

#Accessing the tuple by negative index

print('Last item of tuple = \n',langtuple[-1])
print('First item of tuple =\n',langtuple[-5])

Output

Last item of tuple = 
 Rust
First item of tuple =
 C++

3. Access tuple items by Range positive Indexes


We can access items by specific the range in positive and negative. This is like fetching a slice. Let understand with a code example.

In this example, we are accessing with index [2:5], which means starting from the 2nd index and ending at the 4th index. Index 5 is not included in this.

Program Example

langtuple = ('C#','C++','C','Java','Go','Rust')

#Accessing the tuple by postive index

print('Accessing tuple by range of postive indexes  = \n',langtuple[2:5])

Output

Accessing tuple by range of postive indexes  =  

('C', 'Java', 'Go')

4. Access tuple items by Range of Negative indexes


In this example, we are using slicing to access the range of tuples elements. Similarly for [-5:-1], starting from -2 in reverse and ending at -5. -1 element will not be included while accessing the elements.

Program Example

langtuple = ('C#','C++','C','Java','Go','Rust')


#Accessing the tuple by negative index

print('Accessing tuple by range of negative indexes =\n',langtuple[-5:-1])

Output

Accessing tuple by range of negative indexes =

('C++', 'C', 'Java', 'Go')

Summary

In his post, we have explored different ways to How to access items of Tuples in Python