1

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]])

1 Answer 1

1

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

I understand the In & Out [12]. What I don't understand is if range is (i, i+3) for i in [2, 4, 6], how is the array outputting [2, 3, 4], [4, 5, 6], [6, 7, 8]?
It's range(i, i+3). So if i is 2, we get range(2,5), which expanded to a list is [2,3,4].

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.