How to use Python multiprocessing Pool.map to fill numpy array in a for loop

The following works. First it is a good idea to protect the main part of your code inside a main block in order to avoid weird side effects. The result of pool.map() is a list containing the evaluations for each value in the iterator list_start_vals, such that you don’t have to create array_2D before.

import numpy as np
from multiprocessing import Pool

def fill_array(start_val):
    return list(range(start_val, start_val+10))

if __name__=='__main__':
    pool = Pool(processes=4)
    list_start_vals = range(40, 60)
    array_2D = np.array(pool.map(fill_array, list_start_vals))
    pool.close() # ATTENTION HERE
    print array_2D

perhaps you will have trouble using pool.close(), from the comments of @hpaulj you can just remove this line in case you have problems…

Leave a Comment