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?
Using append() function to create a list of lists in Python. What append() function does is that it combines all the lists as elements into one list. It adds a list at the end of the list.
Lists are useful data structures commonly used in Python programming. A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if you want to create a matrix or need to store a sublist along with other data types.
Python Nested Lists First, we'll create a nested list by putting an empty list inside of another list. Then, we'll create another nested list by putting two non-empty lists inside a list, separated by a comma as we would with regular list elements.
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" 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']]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With