user3232844
user3232844

Reputation: 21

Numpy Multidimensional Array

I'm new to numpy, I don't understand how the following works:

np.array([range(i, i + 3) for i in [2, 4, 6]]) 

and the output is:

array([[2, 3, 4],[4, 5, 6],[6, 7, 8]])

Upvotes: 1

Views: 108

Answers (1)

hpaulj
hpaulj

Reputation: 231665

Do you understand list comprehensions? range?

In [12]: [range(i, i + 3) for i in [2, 4, 6]]
Out[12]: [range(2, 5), range(4, 7), range(6, 9)]

np.array converts the range objects to lists, and then builds the array.

In [13]: [list(range(i, i + 3)) for i in [2, 4, 6]]
Out[13]: [[2, 3, 4], [4, 5, 6], [6, 7, 8]]
In [14]: np.array([list(range(i, i + 3)) for i in [2, 4, 6]])
Out[14]: 
array([[2, 3, 4],
       [4, 5, 6],
       [6, 7, 8]])

So basically it's just a variation on the textbook example of making an array from a list of lists:

In [15]: np.array([[1,2,3],[10,11,12]])
Out[15]: 
array([[ 1,  2,  3],
       [10, 11, 12]])

Upvotes: 1

Related Questions