-1

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:

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:  []
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20
madhurkant
  • 96
  • 9
  • 1
    It seems easier to just use `list2 = []` than `del list2[:]`, but I'm not sure if it's applicable in your case. – qrsngky Mar 16 '23 at 06:45
  • @qrsngky It's not applicable as above code is example only. This is asked for another project. – madhurkant Mar 16 '23 at 06:56

3 Answers3

1

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]]
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20
1

I have modified your code. U can do it in this way as well

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

If you would like insert elements not references, you can use:

x = []
y = [2, 4, 6]
x.append(y[:])
y=[]
Hermann12
  • 1,709
  • 2
  • 5
  • 14