Python – Find first element by second in tuple List
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.
test_list = [(4, 5), (5, 6), (1, 3), (6, 6)]
K = 6
Output : [5, 6]
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.
The original list is : [(4, 5), (5, 6), (1, 3), (6, 9)] The key from value : 
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.
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