Pensu
Pensu

Reputation: 3609

Building a list inside a list in python

I have been trying to add some data in a python list. I am actually going to store the data as a list inside a list. Now, the data is not coming index-wise.

To explain that lets say I have a list of lists 'a'. Now I have data for a[2] before a[1]. And both a[1] and a[2] are lists themselves. Now, obviously I can't assign anything to a[2] before assigning a[1]. And I don't know how much lists would be there. I mean, this is supposed to be dynamic.

Any solution to this, so that I can successfully build the list?

Upvotes: 6

Views: 115841

Answers (6)

Muneeb Ahmad Khurram
Muneeb Ahmad Khurram

Reputation: 670

Simply

I am gonna make it as simple as it gets, No need for fancy modules,

Just make an empty list in the start of the file, and then append that empty list whenever you need it like,

Example

Until the Function get_data give a certain output add empty lists within a list.

#/usr/bin/python3
#coding:utf-8
empty_list = []
r = ''
def get_data():
    # does something here and gives the output
    return output
imp_list = []
while r == %something%:
    r = get_data()
    imp_list.append(empty_list)

Upvotes: 0

Chandan Venkatesh
Chandan Venkatesh

Reputation: 114

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

Upvotes: 4

Viswesn
Viswesn

Reputation: 4880

We can use the first item in the list as an index and then make use of it for adding the right value to it at runtime using the list.

def unclean_(index, val, unclean=None):
   is_added = False
   if unclean is None:
       unclean = []
   length = len(unclean)
   if length == 0:
       unclean.append([index, val])
   else:
       for x in range(length):
            if unclean[x][0] == index:
                unclean[x].append(val)
                is_added = True
       if not is_added:
            unclean.append([index, val])

def terminate_even(x):
    if x % 2 == 0:
        raise Exception("Its even number")

def terminate_odd(x):
    if x % 2 != 0:
        raise Exception("Its odd number")

def fun():
    unclean = []
    for x in range(10):
       try:
            terminate_even(x)
       except:
            unclean_("terminate_even", x, unclean)

    for x in range(10):
       try:
            terminate_odd(x)
       except:
            unclean_("terminate_odd", x, unclean)

    for y in unclean:
        print y

 def main():
    fun()

 if __name__ == "__main__":
    main()

 Output:
 -------
     ['terminate_even', 0, 2, 4, 6, 8]
     ['terminate_odd', 1, 3, 5, 7, 9]

Upvotes: 0

Hellseher
Hellseher

Reputation: 286

I had the same problem, to fill empty list with definite amount of lists. Here is my way out I made a "board" 6x6 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']]

Upvotes: 7

Martijn Pieters
Martijn Pieters

Reputation: 1121456

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.

Upvotes: 10

jabaldonedo
jabaldonedo

Reputation: 26572

You can do it, there is no problem appending an element.

>>> a = [[1,2,3], [10,20,30], [100,200,300]]
>>> a[2].append(400)
 [[1, 2, 3], [10, 20, 30], [100, 200, 300, 400]]
>>> a[1].append(40)
 [[1, 2, 3], [10, 20, 30, 40], [100, 200, 300, 400]]

Upvotes: 2

Related Questions