Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this happening in Python ? Is it do with list mutability?

Tags:

python

Please don't be harsh if my question is very simple or obvious. Am a Python newbie, so just started out.

Actually this was a piece of code I came across on this Stack Overflow only but could not find an answer for why this is happening, so decided to ask it myself.

I wrote the below two programs :

1)

x=[1,2,3]
y=x
print x
y=y+[3,2,1]
print x

Output:

[1,2,3]
[1,2,3]

2)

x=[1,2,3]
y=x
print x
y+=[3,2,1]
print x

Output:

[1,2,3]
[1,2,3,3,2,1]

I can't understand why the two outputs are different in this case ? is y=y+(something) not the same as y+=(something)

what is it that I am missing here ?

Thanks a lot for helping me out on this

like image 694
Aditya Avatar asked Dec 05 '22 08:12

Aditya


2 Answers

This has nothing to do with mutability. It has to do with list objects and references to it.

When you do:

y=x

You are essentially making y refer to the same list that x is referring to.

Now,

y=y+[3,2,1]
  ^-------^  - Create a **new** List is that is equal to concatenation of `y` and [1,2,3]
^---^        - Bind variable `y` to this **new** list.
             - The original list which `x` refered to -- is still *intact*

Again,

y+=[3,2,1]
 ^-------^   - Append [1,2,3] **in-place**. 
             - Since even `x` is pointing to the same list, it gets modified.
like image 155
UltraInstinct Avatar answered Dec 08 '22 05:12

UltraInstinct


y = y+something will replace the contents of y, while y+=something will modify the list in-place.

TL;DR; Code explanation:

>>> x = [1, 2]
>>> y = x
>>> id(y) == id(x)
True
>>> y += [3]
>>> id(y) == id(x)
True
>>> y = y + [3]
>>> id(y) == id(x)
False

Here's a little explanation of what's going on in your code.\

First code

You declared x:

x=[1,2,3]

Then you point y to the value of x:

y=x

After that, here's the tricky part:

y=y+[3,2,1]

This creates a new y variable, replacing the old one. y is no longer related to x. Now, x has it's own place in memory, and y has a separate one

Second code

Declare x:

x=[1,2,3]

Points y to the value of x:

y=x

And lastly:

y+=[3,2,1]

This modifies the list pointed by y in-place. In other words, you're modifying x as well:

If this isn't clear enough, just comment:)

Hope this helps!

like image 29
aIKid Avatar answered Dec 08 '22 05:12

aIKid