Accessing nth element from Python tuples in list

PythonServer Side ProgrammingProgramming

A python list can contain tuples as its elements. In this article we will explore how to access every nth element form the tuples that are present as the elements in the given tuple.

Using index

We can design a for loop to access the elements from the list with the in clause applied for nth index. Then we store the result into a new list.

Example

 Live Demo

Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]

#Given list
print("Given list: ",Alist)

# Use index
res = [x[1] for x in Alist]

print("The 1 st element form each tuple in the list: \n",res)

Output

Running the above code gives us the following result −

Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]
The 1 st element form each tuple in the list:
['3 pm', '12pm', '9 am', '6 am']

Use itemgetter

The itegetter function from operator module can fetch each item form the given iterable till the end of the iterable is searched. In this program we search for index position 2 from the given list and apply a map function to apply the same function again and again to each result from the result of the itemgetter function. Finally we store the result as a list.

Example

 Live Demo

from operator import itemgetter

Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]

#Given list
print("Given list: ",Alist)

# Use itemgetter
res = list(map(itemgetter(2), Alist))

print("The 1 st element form each tuple in the list: \n",res)

Output

Running the above code gives us the following result −

Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]
The 1 st element form each tuple in the list:
[10, 8, 8, 5]
raja
Published on 13-May-2020 14:01:32
Advertisements