Python: Select Value from Tuple List with Conditional Statement

When working with Python and tuples, there may be a need to select a specific value from a list of tuples based on a certain condition. In this case, the best approach is to use a conditional statement within a list comprehension.

├Źndice
  1. Example:
  2. Conclusion:

Example:

            my_list = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
            selected_value = [item[1] for item in my_list if item[0] == 2]

In this example, we have a list of tuples called my_list. Each tuple contains an integer and a string value. We want to select the string value from the tuple where the integer value is equal to 2. To accomplish this, we use a list comprehension with a conditional statement that checks for the value of the first element in each tuple. The list comprehension returns a new list containing only the string value we need.

The resulting selected_value variable will contain the string 'banana', as it is the value associated with the tuple where the integer value is 2.

Conclusion:

Using a conditional statement within a list comprehension is an efficient and effective way to select a specific value from a list of tuples in Python. By isolating the value you need based on a certain condition, you can avoid the need for nested loops or complex logic.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information