...
/Functional Programming Toolkit: "next", "first", and "itertools"
Functional Programming Toolkit: "next", "first", and "itertools"
Learn functional programming in Python.
We'll cover the following...
There’s still one essential tool missing from this list. One common task when working with lists is finding the first item that satisfies a specific condition. This is usually accomplished with a function like this:
def first_positive_number(numbers):for n in numbers:if n > 0:return nmylist = [-1, -10, 5, 7, -3, 8]print( first_positive_number(mylist) )
We can also write this in functional style:
def first(predicate, items):for item in items:if predicate(item):return itemprint( first(lambda x: x > 0, [-1, 0, 1, 2]) )
Using next
You can also return first positive number more concisely like this:
# Less efficientlist(filter(lambda x: x > 0, [-1, 0, 1, 2]))[0]# Efficient but for Python 3next(filter(lambda x: x > 0, [-1, 0, 1, 2]))# Efficient but for Python 2next(itertools.ifilter(lambda x: x > 0, [-1, 0, 1, 2]))
Note:
list(filter(lambda x: x > 0, [-1, 0, 1, 2]))[0]
may elicit anIndexError
if no items satisfy the condition, causinglist(filter())
to return an empty list.
For simple cases you can also rely on next
:
a = range(10)print(next(x for x in a if x > 3))
This will raise StopIteration
if a condition can never be satisfied. In that case, the second argument of next can be used:
a = range(10)print(next((x for x in a if x > 10), 'default'))
Using first
Instead of writing this same function in every program you make, you can include the small, but very useful Python package first
:
from first import first# Returns 42 because it is the first element in the list which is Trueprint(first([0, False, None, [], (), 42]))# Returns -1 as it is the first element in the list which is Trueprint(first([-1, 0, 1, 2]))# Returns 1 as it is the first element in the list which is True# according to the condition provided: (x > 0)print(first([-1, 0, 1, 2], key=lambda x: x > 0))
The key argument can be used to provide a function which receives each item as an argument and returns a Boolean indicating whether it satisfies the condition.
You will notice that we used lambda
in a good number of the examples so far
in this chapter. In the first place, lambda
was added to Python to facilitate functional programming functions such as map
and ...