Python - Find first element by second in tuple List

Python - Find first element by second in tuple List

Let's consider a problem where you have a list of tuples. Each tuple has two elements, and the goal is to find the first element of the tuple given the second element.

Scenario: Given a list of tuples, fetch the first element of the tuple where the second element matches a given value.

Sample Input:

tuple_list = [(10, 'apple'), (20, 'banana'), (30, 'cherry')] search_for = 'banana' 

From this sample input, we aim to find the number (first element) corresponding to the string 'banana' (second element). The desired output is 20.

Using a For Loop:

def find_first_by_second(tuple_list, search_for): for first, second in tuple_list: if second == search_for: return first return None # Return None if the second element is not found in any tuple tuple_list = [(10, 'apple'), (20, 'banana'), (30, 'cherry')] search_for = 'banana' print(find_first_by_second(tuple_list, search_for)) 

Breaking Down the Solution:

  1. We define a function find_first_by_second which takes the list of tuples (tuple_list) and the value to search for (search_for) as arguments.

  2. We iterate over the tuples in tuple_list, unpacking each tuple into first and second variables.

  3. If the second variable matches the search_for value, we return the corresponding first value.

  4. If we complete the loop without finding a match, we return None to indicate the value wasn't found.

Output:

20 

This approach efficiently searches the list of tuples to find the first element based on the second element's value.


More Tags

xml.etree spring-data-elasticsearch spotfire artifacts image-resizing soql imputation checksum broken-pipe amazon-cloudwatchlogs

More Programming Guides

Other Guides

More Programming Examples