Get the first item in a List that matches Condition - Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Get the first item in a list that matches condition
  2. Get the first item in a list that matches condition using a for loop
  3. Get the first item in a list that matches condition using assignment expression
  4. Get the first item in a list that matches condition using filter()

# Get the first item in a list that matches condition - Python

To get the first item in a list that matches a condition:

  1. Use a generator expression to iterate over the list.
  2. Check if each item in the list meets the condition.
  3. Use the next() function to get the first item that meets the condition.
main.py
my_list = [1, 3, 7, 14, 29, 35, 105] first_match = next( (item for item in my_list if item > 14), None ) print(first_match) # ๐Ÿ‘‰๏ธ 29

get first item in list that matches condition

The code for this article is available on GitHub

The same approach can be used to get the first item in any iterable that matches a condition. The iterable doesn't have to be a list object.

We used a generator expression to iterate over the list.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current list item is greater than 14 and return the result.

The next() function returns the next item from the provided iterator.

The function can be passed a default value as the second argument.

If the iterator is exhausted or empty, the default value is returned.

If the iterator is exhausted or empty and no default value is provided, a StopIteration exception is raised.

We specified a default value of None but you can use any other value.

main.py
my_list = [1, 3, 7, 14] first_match = next( (item for item in my_list if item > 14), None ) print(first_match) # ๐Ÿ‘‰๏ธ None

None of the items in the list meet the condition, so the default value is returned.

You can use this approach to get the first item in a list that matches any condition.

main.py
my_list = ['bobby', 'hadz', 'com'] first_match = next( (item for item in my_list if 'bo' in item), None ) print(first_match) # ๐Ÿ‘‰๏ธ bobby

We used the in operator to get the first list item that contains a specific substring.

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

Alternatively, you can use a simple for loop.

# Get the first item in a list that matches condition using a for loop

This is a four-step process:

  1. Use a for loop to iterate over the list.
  2. Check if each item meets the condition.
  3. Once the condition is met, assign the value to a variable.
  4. Use the break statement to break out of the for loop.
main.py
my_list = [1, 3, 7, 14, 29, 35, 105] first_match = None for item in my_list: if item > 29: first_match = item break print(first_match) # ๐Ÿ‘‰๏ธ 35

get first item in list that matches condition using for loop

The code for this article is available on GitHub

We used a for loop to iterate over the list.

On each iteration, we check if the current list item is greater than 29.

If the condition is met, we assign the value of the item to the first_match variable and exit the loop.

The break statement breaks out of the innermost enclosing for or while loop.

There is no need to continue iterating once we've found the first item that meets the condition.

If you need to find all the list items that meet the condition, append the matching elements to a list and remove the break statement.

main.py
my_list = [1, 3, 7, 14, 29, 35, 105] matches = [] for item in my_list: if item > 29: matches.append(item) print(matches) # ๐Ÿ‘‰๏ธ [35, 105]

The list.append() method adds an item to the end of the list.

main.py
my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com']

The method returns None as it mutates the original list.

Alternatively, you can use the newer assignment expression syntax.

# Get the first item in a list that matches condition using assignment expression

This is a two-step process:

  1. Use the any() function to find the first item that matches a condition.
  2. Use the assignment expression syntax to assign the first match to a variable.
main.py
my_list = [1, 3, 7, 14, 29, 35, 105] if any((match := item) > 29 for item in my_list): # ๐Ÿ‘‡๏ธ this runs print(match) # ๐Ÿ‘‰๏ธ 35 else: print('None of the items in the list meets the condition')

get first item in list that matches condition using assignment expression

The code for this article is available on GitHub

The := syntax is called assignment expressions in Python.

Assignment expressions allow us to assign to variables within an expression using the NAME := expression syntax.

The any function takes an iterable as an argument and returns True if any element in the iterable is truthy.

On each iteration, we check if the current item is greater than 29.

If the condition is met, the value of the item gets assigned to the match variable and the if block runs.

If the condition is never met, the else block runs.

# Get the first item in a list that matches condition using filter()

You can also use the filter() function to get the first item in a list that matches a condition.

main.py
my_list = [1, 3, 7, 14, 29, 35, 105] first_match = next(filter(lambda x: x > 14, my_list), None) print(first_match) # ๐Ÿ‘‰๏ธ 29

get first item in list that matches condition using filter

The code for this article is available on GitHub

The filter() function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The lambda function we passed to filter gets called with each element in the list.

The function checks if each element is greater than the number 14 and returns the result.

The next() function returns the first matching element or None if no element matches the condition.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev