Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 751
CommanderPO Avatar asked Jun 12 '17 14:06

CommanderPO


People also ask

How do you create a list in for loop?

You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.

How do you make a list of lists in Python?

What is a list of lists? In any programming language, lists are used to store more than one item in a single variable. In Python, we can create a list by surrounding all the elements with square brackets [] and each element separated by commas. It can be used to store integer, float, string and more.

Can you loop through multiple lists?

Iterate over multiple lists at a time We can iterate over lists simultaneously in ways: zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.


3 Answers

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.

like image 84
Ilario Pierbattista Avatar answered Sep 18 '22 21:09

Ilario Pierbattista


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)]
like image 43
ettanany Avatar answered Sep 22 '22 21:09

ettanany


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)]
like image 34
Taku Avatar answered Sep 22 '22 21:09

Taku