Building a list inside a list in python

Building a list inside a list in python

You could append empty lists until you have enough to access the index you have data for:

while len(outerlist) <= idx:
    outerlist.append([])

However, you may want to use a dictionary instead, letting you implement a sparse object instead. A collections.defaultdict() object is especially useful here:

from collections import defaultdict

data = defaultdict(list)

data[2].append(3)
data[5].append(42)

data now has keys 2 and 5, each a list with one element. No entries for 0, 1, 3, or 4 exist yet.

I had the same problem, to fill empty list with definite amount of lists.
Here is my way out
I made a board 6×6 filled with O, just for instant:

board = []    
for i in range(6): # create a list with nested lists
    board.append([])
    for n in range(6):
        board[i].append(O) # fills nested lists with data

Result:

[[O, O, O, O, O, O],
 [O, O, O, O, O, O],
 [O, O, O, O, O, O], 
 [O, O, O, O, O, O],
 [O, O, O, O, O, O],
 [O, O, O, O, O, O]]

Building a list inside a list in python

I think this solution solves your problem.

Create the secondary list(inside_list) local to the for loop

    outside_list=[]
    for i in range(0,5):
        inside_list=[]
        inside_list.append(i)
        inside_list.append(i+1)
        outside_list.append(inside_list)

       #you can access any inside_list from the outside_list and append     
        outside_list[1].append(100)
        print(outside_list)

Output:

[[0, 1], [1, 2, 100], [2, 3], [3, 4], [4, 5]]

Leave a Reply

Your email address will not be published. Required fields are marked *