I have the following nested loop:
for i in range(1,5):
for j in range(0,i):
j
I get strange results when I try to re-express the same using the list comprehension
[j for j in range(0,i) for i in range(1,5)]
Firstly, can someone explain the output with this list comprehension? I can't really seem to understand what Python is doing here.
Secondly, can the inner for
's iterator not explicitly depend on the outer index?
Thirdly, is there any way to modify the list comprehension to get the same result as the nested for loop written at the beginning?
Your list comprehension doesn't do anything as it does not run without i
already been defined outside the list comprehension.
To achieve what you want (and yes, this is counter intuitive ) you need to do this:
[j for i in range(1,5) for j in range(0,i)]
This will yield:
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]
which is the same order as your nested for loops.