Reputation: 11
How is this range function working here? It is generating an answer but I can't understand it it has created the resulted ndarray.
np.array([range(i, i + 3) for i in [2, 4, 6]])
Upvotes: 1
Views: 42
Reputation: 1305
A range is a sequence of numbers. The function range normally accepts 1-3 params range(start, stop[, step])
. In your case the step is ommited, thus the default 1 is applied. So it is creating ranges from a given number i
to that number +3 → range(i, i + 3)
The list comprehension, makes that the given number i
will iterate over the list [2,4,6]
, so you will create a list with 3 sublists: [range(2,2+3), range(4,4+3), range(6,6+3)]
wich equals to [[2,3,4], [4,5,6], [6,7,8]]
.
Finally, all is wrapped as a numpy array and the output is → array([[2, 3, 4],[4, 5, 6],[6, 7, 8]])
Upvotes: 1