So I have been learning list comprehensions in python and don't understand the logic of how nested list comprehensions work in python. Consider the following snippets of codes :
####TRADITIONAL EXAMPLE-1###
L = []
for i in range(5):
for j in range(4):
L.append(j)
#output of l-> [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
####TRADITIONAL EXAMPLE-2###
K = []
for i in range(5):
for j in range(4):
K.append(i)
#output of k -> [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
Okay, this all makes sense, but when I want to recreate these using list comprehensions the logic doesn't make sense to me. Now consider these examples :
###LIST COMPREHENSION EXAMPLE-3####
L1 = [j for j in range(4) for i in range(5)]
#Output of L1 -> [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
###LIST COMPREHENSION EXAMPLE-4####
K1 = [i for j in range(4) for i in range(5)]
#Output of K1 -> [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
###LIST COMPREHENSION EXAMPLE-5####
Q = [[j for j in range(4)] for i in range(5)]
#Output of Q -> [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
###LIST COMPREHENSION EXAMPLE-6####
Q1 = [[i for j in range(4)] for i in range(5)]
#output of Q1 -> [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]
So I don't know why but I expect the output L and L1 (Examples 1 and 3) to be the same irrespective of using the traditional way or list comprehension way and the same goes for K and K1 (Examples 2 and 4) especially when I compare the output of Q and Q1 (Eg 5 & 6). Like compare Q1 and K1 (Example 4 and 6), they are almost following the same syntax but the output is way different.
I hope I am able to clarify myself about my confusion here based on the output each of these list comprehension gives compared to the traditional way of doing it. I tried searching online and following tutorials but they just state examples not explain the working or logic behind it. I just don't want to mug up the outputs without knowing the reason behind why the output is what it is. Thanks for the help :)