I am trying to create lists based on a value given by the user input and then I would like to add those lists created to a Parent list where they all can be accessed and used.
For example, I want the for loop to grab the number entered by the user, and based on that number it needs to create lists numbered from 1 to whatever they chose. At the end of each repetition I would like to add the created list to a parent list.
Here is what I have so far, I am struggling in adding them to the parent list I guess.
lists = int(input("How many lists do you want? "))
varname = 'iteration_number_'
parent_list = []
for i in range(lists):
iteration_number = i 1 #So it does not start from 0
iteration_names = varname str(iteration_number) #merging the name and the number
x = parent_list.append(exec(f"{iteration_names} = []")) #creating lists with that name
try:
iteration_number_1.append("Cow") # appends Cow to the first list if existing
iteration_number_2.append("Moo") # appends Moo to the first list if existing
print(iteration_number_1)
print(iteration_number_2)
except NameError:
pass
print(parent_list)
parent_list[0].append("This is list iteration_number_1 but I'm not working")
The last part of the code doesn't work as planned. In my head when I print parent_list I should get [[iteration_number_1], [iteration_number_2]] and they can be accessed like this
parent_list[0].append("Hello") #appending to the iteration_number_1 list
Does anyone know a better idea? or how to make this idea work?
CodePudding user response:
The programmers call them nested lists:
myNestedList = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
You can access the inner lists this way:
>>> myNestedList[0] # Get the first row
[1, 2, 3]
>>> myNestedList[0][2]
3
You can append elements to the inner lists this way:
>>> myNestedList[0].append(10)
>>> myNestedList
[[1, 2, 3, 10], [4, 5, 6], [7, 8, 9]]
CodePudding user response:
You could try to a dictionary with the key as a string to the iteration number and the value as a list:
d = {}
d["iteration_number_1"] = []
...
d["iteration_number_1"].append("hello")
