Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructive nature operation in python? [duplicate]

Tags:

python

Possible Duplicate:
How to clone a list in python?

I found some interesting results

a = [1, 2] 
b=a 
b.append(3) 
print a, b

#=> [1,2,3] [1,2,3]


a = [1, 2] 
b=a 
b += [3] 
print a, b

#=> [1,2] [1,2,3]

It seems like some operation have change the referenced value, some create a new. I remember in Ruby it can use ! to indicate which method have this destructive nature. Does python have the similar way to let me distinguish them? or providing a list to show all the most commonly used one?

like image 280
mko Avatar asked Sep 26 '26 23:09

mko


1 Answers

Contrary to some existing answers here, the real reason actually the opposite. += is meant to be an in-place operator that modifies self in Python. But there's some catch to it.


For immutable types such as tuples and strings, my_tuple += (1, ) is equivalent to my_tuple = my_tuple + (1, ) which creates a new object then assigns it to my_tuple:

>>> my_tuple = (1,2,3)
>>> t = my_tuple
>>> t += (2,)
>>> t
(1, 2, 3, 2)
>>> my_tuple
(1, 2, 3)

This is because immutable types such as tuples and strings do not implement __iadd__ (you can check by dir(tuple) for example). And in this case it falls back to use __add__ instead. This will create a new object and assign it to the original variable.


For some mutable types such as lists and dictionaries, however, __iadd__ is implemented, and += will be calling it instead:

>>> inspect.getdoc(list.__iadd__)
'x.__iadd__(y) <==> x+=y'

>>> a = [1,2,3]
>>> b = a
>>> b += [4]
>>> b
[1, 2, 3, 4]
>>> a
[1, 2, 3, 4]

So for mutable types, this in-place operation is performed (by modifying self) and the original object will be updated.

like image 69
K Z Avatar answered Sep 28 '26 13:09

K Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!