1
x=['0100', '1111', '1001', '1011']
y=x
y.remove('0100')
print(x)

the code above returns:['1111', '1001', '1011'] I am a begginer programmer and I want to know why the remove() function also modifies the x list instead of the intended y list? The code is run in python 3.4.2. How do I fix this so that only the y list will be modified?

tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • 3
    `y=x` does not copy the list. try `y=x[:]` or `y=list(x)` – tobias_k Mar 14 '15 at 16:23
  • possible duplicate of [How to clone or copy a list in Python?](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python) – tobias_k Mar 14 '15 at 16:24
  • Try `id(x)` and `id(y)` to see that they reference the same object. – Akavall Mar 14 '15 at 16:24
  • You have to learn what _reference_ is and what is difference between _mutable_ and _immutable_ types in Python. _list_ is mutable type, so assigning will create new reference to a new object – myaut Mar 14 '15 at 16:25
  • @Akavall: Python has more obvious way to do that: `y is x`. – myaut Mar 14 '15 at 17:20
  • @myaut, I think actually seeing memory address (OK identity of an object in python) helps the point sink. It helped me, when I was first learning this stuff. – Akavall Mar 14 '15 at 17:31

3 Answers3

1

it's because you copied the reference of x into y. you can create a copy by y = list(x).

for example:

x=['0100', '1111', '1001', '1011']
y = list(x)
y.remove('0100')
print(x)
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
  • You may want to mention [Shallow and deep copy operations](https://docs.python.org/3/library/copy.html) – motoku Mar 14 '15 at 16:32
0

Simple - x and y are not lists, they are just references to list. there is some point in memory containing list data and both x and y just know where it is. So when you do y = x and change list referenced by y, this change will be reflected at print(x).

iced
  • 1,562
  • 8
  • 10
0

You have to understand the difference between the variable and the what this variable contains. With this:

x=['0100', '1111', '1001', '1011']
y=x

X and y are exactly the same, you have to copy x and make the assignation you can do it this way: y=x[:], this code copy the content of x and assign it to y

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
JoseM LM
  • 373
  • 1
  • 8