Last updated: Apr 10, 2024
Reading timeยท4 min
To get the first item in a list that matches a condition:
next()
function to get the first item that meets the condition.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
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.
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.
StopIteration
exception is raised.We specified a default value of None
but you can use any other value.
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.
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.
This is a four-step process:
for
loop to iterate over the list.break
statement to break out of the for
loop.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
We used a for
loop to iterate over the list.
On each iteration, we check if the current list item is greater than 29
.
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.
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.
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.
This is a two-step process:
any()
function to find the first item that matches a condition.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')
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.
You can also use the filter()
function to get the first item in a list that
matches a condition.
my_list = [1, 3, 7, 14, 29, 35, 105] first_match = next(filter(lambda x: x > 14, my_list), None) print(first_match) # ๐๏ธ 29
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.