Need help understanding this range function

Viewed 82

I'm a new programmer and I don't understand:

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

I know that in the range function there is a start, stop and step, but it's written quite differently here.

The output is a 3*3 array

234
456
678

I don't understand how this array came about. What does the I+3 mean? Are the 2,4,6 x values? What exactly if the for loop doing in this case? What is it iterating over?

Thanks for the help.

2 Answers

If I break down that line of code a little bit I can show you what happens.

The following line is a list comprehension, it's saying return I where I is set to each number in the list [2,4,6]. This returns a list that looks like [2,4,6]. So that's essentially useless because you're not manipulating your original list.

[I for I in [2,4,6]]

when you put this inside np.array() it just creates an array from your list.

Now with the following code, your going through each number in the range 2-5 not including 5 (5 is I+3)

for i in range(2,5):
     print(i)
2
3
4

You could also do

for i in range(2,5):
     print(np.array([range(2,4)]))
 
[[2 3]]
[[2 3]]
[[2 3]]

Which is a loop that executes 3 times, and prints an array which contains a range from 2-4 in it.

When you combine everything in

[range(I, I+3) for I in [2,4,6]]

You're saying for each number in the list [2,4,6] return a range from that number up to that number + 3 and put that in a list, which returns

[range(2, 5), range(4, 7), range(6, 9)]

Then you convert that to an array to get

array([[2, 3, 4],
       [4, 5, 6],
       [6, 7, 8]])
np.array(                      # This is a numpy library's 2D data structure array.
    [
        range(i, i+3)          # range function which produces iterator from i to i+2 (exclusive of end) i.e. if i = 1, range(1, 4) will give [1, 2, 3]
        for i in [2,4,6]       # Basic list comprehension for loop
    ]
)
Related