Extract any element from list of tuples Python

In this article, we are going to Extract any element from list of tuples Python. We are going to use the map() function for this program.The map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple, etc.)

Syntax

 map(func, iter)

Parameters :

  • func : It is a function to which a map passes each element of a given iterable.
  • iter : It is iterable which is to be mapped.
  • Returns: Returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)

Program to Extract any element from list of tuples Python


  • Create a list of tuples.
  • Now enter the index of tuples for extracting the element of tuples.
  • In the first method, I use the map and lambda functions.
  • In the lambda function, I pass the index of tuples elements.
  • The map() function is used to map the particular elements that are extracted and then print the new result list.
  • In the second method, I create the lambda function and a list separated.
  • Using for loop I iterate the list of tuples and called the lambda function and append the extracted element in a new list.
  • At last print the new list.
OrgList =[('Rahul', 56, 118), ('Vidhi', 32, 120), ('Nanoha', 71, 67), ('Akkira', 13, 81)]

index=int(input("Enter Index(0-2) "))
if index==0:
    print("Extracting the Index 0:")
elif index==1:
    print("Extracting the Index 1:")
elif index==2:
    print("Extracting the Index 2:")
else:
    print("Please Select Index from 0 to 2 only")
	
print("First Method")
res=list(map(lambda x:x[index],OrgList)) 
print(res)


print("Second Method")
a=lambda a:a[index]
new_list=[]
for i in OrgList:
    new_list.append(a(i))
print(new_list)

Output:

Enter Index(0-2) 2
Extracting the Index 2:
First Method
[118, 120, 67, 81]
Second Method
[118, 120, 67, 81]