1

Here I am learning mutable concept using list in python,

In [114]: x=[1,2]

In [115]: y =x

In [116]: id(y)==id(x)
Out[116]: True

From above x and y sharing same state. I have observed two cases below,

1) Here mutable concept working because it shares same state,

In [123]: y +=[1,3]

In [124]: id(y)==id(x)
Out[124]: True

In [125]: y
Out[125]: [1, 2, 1, 3]

In [126]: x
Out[126]: [1, 2, 1, 3]

2) Here mutable concept not working because it didn't shares same state,

In [130]: y =y+[1,3]

In [131]: id(y)==id(x)
Out[131]: False

In [132]: x
Out[132]: [1, 2]

In [133]: y
Out[133]: [1, 2, 1, 3]

Why mutable concept not working second case ?

y += [1,3] and y =y+[1,3] are not equal ?

dhana
  • 6,487
  • 4
  • 40
  • 63

2 Answers2

1
y += [1,3]   # Means append to y list [1,3], object stays same
y = y+[1,3]  # Means create new list equals y + [1,3] and write link to it in y
ndpu
  • 22,225
  • 6
  • 54
  • 69
0

no, they are not. op= (where op can be +, *, -, /, ...) are "in place" operators.

So they modify the left side of the assignment if they can.

X op Y, on the other hand, creates a new instance and puts the result there.

That means

 y = [1,2]
 y += [3,4]

is the same as

 y = [1,2]
 y.extend([3,4])

while

 y = [1,2]
 y = y + [3,4]

is the same as

 y = [1,2]
 tmp = list(y) # Create copy of y
 tmp.extend([3,4])
 y = tmp
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820