I'd like to use all(map(func, iterables))
, because it is clear, but I'm very interested in whether this approach is optimized? For example, if any calculated result of map()
is not True
mapping should stop.
Example from my project:
for item in candidate_menu:
if not item.is_max_meals_amount_ok(daily_menus):
return False
return True
I prefer to use functional-like style:
all(map(operator.methodcaller('is_max_meals_amount_ok', daily_menus), candidate_menu)
I there any optimization for all(map(...))
or any(map(...))
in Python?
Edit: Python 2.7 on board.
In addition to all(func(i) for i in iterable)
suggested by others, you can also use itertools.imap
- all(imap(func, iterable))
. Compared to map
, imap
is an iterator thus if all
stops consuming from it, it won't advance any further.
If you want to get lazy evaluation in Python 2.x, try:
all(func(i) for i in iterables)
This will not build the whole list then evaluate, unlike map
. In Python 3.x, map
returns an iterator so will be lazy by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With