11

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.

Georgy
  • 12,464
  • 7
  • 65
  • 73
CommanderPO
  • 113
  • 1
  • 1
  • 5

5 Answers5

21

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.

Ilario Pierbattista
  • 3,175
  • 2
  • 31
  • 41
10

You can use this one line code with list comprehension to achieve the same result:

new_list = [[i for i in range(10)] for j in range(10)]
ettanany
  • 19,038
  • 9
  • 47
  • 63
6

Alternatively, you only need one loop and append range(10).

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

Or

newlist = [list(range(10)) for _ in range(10)]
Taku
  • 31,927
  • 11
  • 74
  • 85
3

Or just nested list comprehension

[[x for x in range(10)] for _ in range(10)]
vZ10
  • 2,468
  • 2
  • 23
  • 33
  • 1
    This by itself won't do anything here. For someone who's struggling with two for loops (OP), you should probably add the important `new_list =` part... Also, it's probably neater to do `[list(range(10)) for _ in range(10)]`, although mostly opinion based. – Markus Meskanen Jun 12 '17 at 15:10
2

You should put a intermiate list to get another level

newlist = []
for x in range(10):
    temp_list = []
    for y in range(10):
        temp_list.append(y)
    newlist.append(temp_list)
Tbaki
  • 1,013
  • 7
  • 12