Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an all(map(...)) optimization in Python?

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.

like image 947
Viach Kakovskyi Avatar asked Feb 24 '14 20:02

Viach Kakovskyi


2 Answers

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.

like image 104
Maciej Gol Avatar answered Oct 05 '22 01:10

Maciej Gol


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.

like image 20
jonrsharpe Avatar answered Oct 05 '22 03:10

jonrsharpe