
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Access Nth Element from Python Tuples in List
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
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
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]