Python How to fix this

Viewed 34
 list1 =[1,2,3]
 list2 = [4,5,6]
 list1.append(list2)
 list2.pop()
 print(list1)

Display [1, 2, 3, [4, 5]]

the value in list1 disappear

2 Answers

You need to make a copy of list2 and append that instead.

For example:

 list1 =[1,2,3]
 list2 = [4,5,6]
 list1.append(list2[:])
 list2.pop()
 print(list1)

Adding the [:] at the end of list2 in the append statement makes a copy of the list.

So your output will be:

[1, 2, 3, [4, 5, 6]]

list2 will still have it's last value removed, but it will have no effect on list1

Python list pop() removes and returns the last value from the List or the given index value.

that's why the last index of the last list will be deleted

Related