0

I have come across a very interesting problem with list.append and list.pop as in the code below

x = [1,2]
y = []
y.append(x)
print(y)
print("------")
x.pop()
print(y)

Output is

[[1, 2]]
------
[[1]]

Is there any way to maintain print(y) as [[1,2]] Thanks

EDIT: Also, does anyone know why this happens?

EML
  • 395
  • 1
  • 6
  • 15
  • `y.append(x.copy())` – sanyassh Jun 01 '19 at 22:58
  • Thanks. Do you know why this happens? – EML Jun 01 '19 at 22:58
  • 3
    The reference to the object is the same both in the variable `x` and in the list `y`. – N Chauhan Jun 01 '19 at 22:59
  • 2
    In python lists are mutable secuence of objects. That means that x really is not a list, but a reference to the list, so when you do y=x, you are only copying the reference, not the list. If you change the original list (x) the other list (y) will change too. To avoid it, as @Sanyash says, you need to use x.copy() and make another copy of the list – nacho Jun 01 '19 at 23:07

1 Answers1

2

When you do

y.append(x)

You are adding a reference to the x object into the y list. When you do x.pop(), you are doing that operation on all references of x, which includes the one within y.

To make a separate copy of that list, you can either do

y.append(x[:])

Which is a slice returning all items in the list - a copy, essentially. If you do not like this syntax and you are in Python 3, you can use

y.append(x.copy())

This may be a bit clearer in your code. See this answer for a few more alternatives to copy a list.

miike3459
  • 1,431
  • 2
  • 16
  • 32