Home > Back-end >  Python double loop for
Python double loop for

Time:09-01

X = [[0 for i in range(6)] for j in range(6)] I'm used to simple for loops like: for i in range(5): but i couldn't understand this code! what's the meaning of the "0" at the beginning?

my code:

for i in range(6):
    for j in range(6):

but what should i put inside the loop? Thanks

CodePudding user response:

this is a list comprehension, its basically the same as saying :

X = []
for i in range(6):
    sublist=[]
    for j in range(6)
        sublist.append(0)
    X.append(sublist)

so you end with a nested list filled with 0s in the end, but the list comprehension is much more compact and faster in certain cases

CodePudding user response:

This is called List Comprehension

X = [[0 for i in range(6)] for j in range(6)]

here for each index of j, a list should be generated by [0 for i in range(6)]

here, [0 for i in range(6)], for each index of i, 0 is being added to the list and generating a list something like this [ 0, 0, 0, 0, 0, 0 ]. This list will be generated 6 times, since j iterate from 0-5 (6 times).

So, the output should be [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

  • Related