...

/

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:

Press + to interact
def first_positive_number(numbers):
for n in numbers:
if n > 0:
return n
mylist = [-1, -10, 5, 7, -3, 8]
print( first_positive_number(mylist) )

We can also write this in functional style:

Press + to interact
def first(predicate, items):
for item in items:
if predicate(item):
return item
print( first(lambda x: x > 0, [-1, 0, 1, 2]) )

Using next

You can also return first positive number more concisely like this:

Press + to interact
# Less efficient
list(filter(lambda x: x > 0, [-1, 0, 1, 2]))[0]
# Efficient but for Python 3
next(filter(lambda x: x > 0, [-1, 0, 1, 2]))
# Efficient but for Python 2
next(itertools.ifilter(lambda x: x > 0, [-1, 0, 1, 2]))

Note: list(filter(lambda x: x > 0, [-1, 0, 1, 2]))[0] may elicit an IndexError if no items satisfy the condition, causing list(filter()) to return an empty list.

For simple cases you can also rely on next:

Press + to interact
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:

Press + to interact
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:

Press + to interact
from first import first
# Returns 42 because it is the first element in the list which is True
print(first([0, False, None, [], (), 42]))
# Returns -1 as it is the first element in the list which is True
print(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 ...

Access this course and 1400+ top-rated courses and projects.