1

Suppose there is a 2-dimensional numpy array of shape (10000, 100) and size 1000000. There is also a 1-dimensional list of length 1000000. What would be the fastest way to assign all the values in the list to the array? My solution is:

my_array = np.zeros([10000, 100]) 
my_list = range(1000000)
length_of_list = len(my_list)

for i in range(length_of_list):                  
    my_array.flat[i] = my_list[i]

Is there maybe a better one?

1
  • my_array.flat[:] = my_list is possible. It avoids the for loop, But turns out to run at the same speed. Commented Jun 5, 2014 at 7:54

1 Answer 1

3

I thought that turning the list to an array and reshaping it then would be the fastest solution, but it turned out in my setup @M4rtini's one-liner is even faster:

In [25]: %%timeit -n 10 
   ....: for i in range(length_of_list):                  
   ....:     my_array.flat[i] = my_list[i]
   ....: 
10 loops, best of 3: 420 ms per loop

In [26]: %timeit -n 10 my_array.flat[:] = my_list
10 loops, best of 3: 119 ms per loop

In [27]: %timeit -n 10 my_array = np.array(my_list).reshape(10000, 100)
10 loops, best of 3: 133 ms per loop
Sign up to request clarification or add additional context in comments.

1 Comment

seems like i messed up my timings :) forgot to convert the range object to a list first, still getting used to py3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.