Home > Back-end >  Appending a values of a list to a list of lists
Appending a values of a list to a list of lists

Time:04-07

I have a list list1 = [1, 2, 3] and I would like to append it to another list, such that I get list_of_lists = [[1, 2, 3]]. I would like then to append more and get something like list_of_lists = [[1, 2, 3], [4, 5, 6]].

My problem is that I am doing this in a loop and I am using the same list to be appended many times with different values, however when I clear the list with list1.clear(), then also the values I appended are cleared. Here the full code

list_of_lists = []
list1 = [1, 2, 3]

list_of_lists.append(list1)
list1.clear()

print(list_of_lists)

the output is [[]]. How should I fix this? Thanks

CodePudding user response:

Everything is fine, the only thing you would need to change is when you add list1 to list_of_lists add it as such:

list_of_lists.append(list(list1))

Everything should work after that.

CodePudding user response:

Are you looking for something like this?

listOfLists = []
list1 = [1,2,3]
list2 = [4,5,6]

listOfLists.append(list1)
print(listOfLists)
listOfLists.append(list2)
print(listOfLists)

or something like this?

listOfLists = []
list1 = [1,2,3]
listOfLists.append(list1)
print(listOfLists)
list1 = []
# append numbers to list1 in loop

    list1.append(x)

listOfLists.append(list1)
print(listOfLists)
  • Related