Retrieve the nth elements from a list of tuples

Submitted 3 years, 6 months ago
Ticket #210
Views 214
Language/Framework Python
Priority Medium
Status Closed

I have a list of tuples like

data = [(1,2,3),('soni','ansh','shivika'),('female','male','female')]

Now I want to extract the 2nd element from the tuples of list i.e.,

Output should be like:

[2, 'ansh', 'male']

How can I acheive this?

Submitted on Oct 06, 20
sai
add a comment

2 Answers

# get nth tuple element from list 
# using list comprehension  
  
# initializing list of tuples 
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] 
  
# printing original list  
print ("The original list is : " + str(test_list)) 
  
# using list comprehension to get names 
res = [lis[1] for lis in test_list] 
      
# printing result 
print ("List with only nth tuple element (i.e names) : " + str(res)) 

OR

# get nth tuple element from list 
# using map() + itergetter() 
from operator import itemgetter 
  
# initializing list of tuples 
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] 
  
# printing original list  
print ("The original list is : " + str(test_list)) 
  
# using map() + itergetter() to get names 
res = list(map(itemgetter(1), test_list)) 
      
# printing result 
print ("List with only nth tuple element (i.e names) : " + str(res)) 

Submitted 3 years, 6 months ago

thank you Nmadhusmita018 for your answer.But I want efficient code

- sai 3 years, 6 months ago


Verified

​
data = [(1,2,3),('soni','ansh','shivika'),('female','male','female')]
n = 1
print([x[n] for x in data])

​

this is another way.....

Submitted 3 years, 6 months ago


Latest Blogs