Skip to content
Related Articles

Related Articles

Improve Article

Python – Find first element by second in tuple List

  • Last Updated : 03 Jul, 2020

Sometimes, while working with Python records, we can have a problem in which we need to find the first element of tuple from the given second element. This kind of problem can occur in domains such as web development. Let’s discuss certain ways in which this task can be performed.

Input :
test_list = [(4, 5), (5, 6), (1, 3), (6, 6)]
K = 6
Output : [5, 6]

Input :
test_list = [(4, 5), (5, 7), (1, 3), (6, 8)]
K = 6
Output : []

Method #1 : Using list comrehension
This is one of the ways in which this task can be performed. In this, we iterate for each tuple, and if we find key matching to value, we store in result list.




# Python3 code to demonstrate working of 
# Find first element by second in tuple List
# Using list comprehension
  
# initializing list
test_list = [(4, 5), (5, 6), (1, 3), (6, 9)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 6
  
# Find first element by second in tuple List
# Using list comprehension
res = [x for (x, y) in test_list if y == K]
  
# printing result 
print("The key from value : " + str(res)) 
Output :



The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)]
The key from value : [5]

 

Method #2 : Using next() + generator expression
This is yet another way in which this task can be solved. In here, the next() is used to get the successive elements and generator expression is used to check for the logic.




# Python3 code to demonstrate working of 
# Find first element by second in tuple List
# Using next() + generator expression
  
# initializing list
test_list = [(4, 5), (5, 6), (1, 3), (6, 9)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 6
  
# Find first element by second in tuple List
# Using next() + generator expression
res = next((x for x, y in test_list if y == K), None)
  
# printing result 
print("The key from value : " + str(res)) 
Output :
The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)]
The key from value : 5

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :