How to create and fill a list of lists in a for loop

CommanderPO picture CommanderPO · Jun 12, 2017 · Viewed 57.3k times · Source

I'm trying to populate a list with a for loop. This is what I have so far:

newlist = []
for x in range(10):
    for y in range(10):
        newlist.append(y)

and at this point I am stumped. I was hoping the loops would give me a list of 10 lists.

Answer

Ilario Pierbattista picture Ilario Pierbattista · Jun 12, 2017

You were close to it. But you need to append new elements in the inner loop to an empty list, which will be append as element of the outer list. Otherwise you will get (as you can see from your code) a flat list of 100 elements.

newlist = []
for x in range(10):
    innerlist = []
    for y in range(10):
        innerlist.append(y)
    newlist.append(innerlist)

print(newlist)

See the comment below by Błotosmętek for a more concise version of it.