Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Appending a values of a list to a list of lists

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading