Oct-17-2018, 03:19 AM
Ah, yes, list comprehensions. They're a trip when you first learn about them.
The portion you're referencing is equivalent to:
The range() function returns an iterator starting at the first value provided and incrementing to the second value. So, range(i, i + 3) will start at "i" and end at "i + 3". For the first iteration of the loop, i = 2 and the call will be for range(2, 5), which can be used to produce the list [2, 3, 4].
In short, the first part of the list comprehension instructs the interpreter what to add to the list while the second part provides a loop expression to direct the process. Each time the loop iterates, it appends a new range() to the list. However, list comprehensions are faster than the equivalent code I wrote above.
To accomplish this without numpy:
The portion you're referencing is equivalent to:
out = [] for i in [2, 4, 6]: out.append(list(range(i, i + 3)))It will loop over the list [2, 4, 6] assigning the variable "i" to the value of the current iteration each time. So, the first time through, i = 2; the second time, i = 4; etc.
The range() function returns an iterator starting at the first value provided and incrementing to the second value. So, range(i, i + 3) will start at "i" and end at "i + 3". For the first iteration of the loop, i = 2 and the call will be for range(2, 5), which can be used to produce the list [2, 3, 4].
In short, the first part of the list comprehension instructs the interpreter what to add to the list while the second part provides a loop expression to direct the process. Each time the loop iterates, it appends a new range() to the list. However, list comprehensions are faster than the equivalent code I wrote above.
To accomplish this without numpy:
[list(range(i, i + 3)) for i in [2, 4, 6]]