Advertisements
I have:
- A small python list, say
list2
,[2, 4, 6]
- A large, initially empty, python list, say
list1
,[]
What I need:
list2
to be added inlist1
as a small list inside large list.- After addition all elements of small list be deleted.
The python code I have written for the purpose:
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]]