close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to create and fill a list of lists in a for loop in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    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.

  2. create and fill a list of lists in a for loop

    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.

Method 1

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.

Method 2

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)]

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read