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

Insert python list into another list

I have:

  1. A small python list, say list2, [2, 4, 6]
  2. A large, initially empty, python list, say list1, []

What I need:

  1. list2 to be added in list1 as a small list inside large list.
  2. After addition all elements of small list be deleted.

The python code I have written for the purpose:

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

list1 = []
list2 = [2, 4, 6]
list1.append(list2)
del list2[:]
print("List 2: ", list2)
print('List 1: ', list1)

The expected output was:

List 2:  []
List 1:  [[2, 4, 6]]

But What I got is this:

List 2:  []
List 1:  []

>Solution :

You are appending list2 as a refrence. so when you apply del list2[:] it is clearing the list that was appended to list1 also.

To resolve this issue you can append list2. by first creating a copy and than appending.

Code:

list1 = []
list2 = [2, 4, 6]
list1.append(list2.copy())  
del list2[:]
print("List 2: ", list2) #[]
print('List 1: ', list1) #[[2, 4, 6]]
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