...
/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:
We can also write this in functional style:
Using next
You can also return first positive number more concisely like this:
Note:
list(filter(lambda x: x > 0, [-1, 0, 1, 2]))[0]may elicit anIndexErrorif no items satisfy the condition, causinglist(filter())to return an empty list.
For simple cases you can also rely on next:
This will raise StopIteration if a condition can never be satisfied. In that case, the second argument of next can be used:
Using first
Instead of writing this same function in every program you make, you can include the small, but very useful Python package first:
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 filter. This ...