Search code examples
pythonfor-loopcoding-styleiteration

map, then iterate - why?


In DEAP example (Python framework) there is a code:

# Evaluate the entire population
fitnesses = list(map(toolbox.evaluate, pop))
for ind, fit in zip(pop, fitnesses):
    ind.fitness.values = fit

why they use map, then for? Why not just:

for ind in pop:
    ind.fitness.values = toolbox.evaluate(ind)

Solution

  • I'm one of the DEAP developer.

    We use the map so that we can easily parallelize the evaluation by replacing the map by a parallel map.

    Later in the examples, we use a toolbox with a map registered in it (__buitins__.map) that can be replaced by multiprocessing.Pool.map or scoop.futures.map. You can look at the documentation for how to distribute the evaluation here