Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does python list L += x behaves differently than L = L + x? [duplicate]

ls = [1,2,3]
id(ls)
output: 4448249184  # (a)

ls += [4]
id(ls)
output: 4448249184  # (b)

ls = ls + [4]
id(ls)
output: 4448208584   # (c)

Why are (a) and (b) the same, but (b) and (c) are different?

Isn't L += x the same as L = L + x?

like image 979
Randy Sugianto 'Yuku' Avatar asked Feb 17 '26 03:02

Randy Sugianto 'Yuku'


2 Answers

Using +=, you are modifying the list in plac, like when you use a class method that append x to L (like .append, .extend…). This is the __iadd__ method.

These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).

Using L = L + x, you are creating a new list (L+x) that you are affecting to a variable (in this case L).

See also different behaviour for list __iadd__ and __add__

like image 194
fredtantini Avatar answered Feb 19 '26 16:02

fredtantini


Augmented assignment in List case is different. it is not actual assignment like in integer so that

a += b

is equal to

a = a+b

while in case of List it operate like:

list += x

is:

list.extends(x)
like image 43
Vishnu Upadhyay Avatar answered Feb 19 '26 17:02

Vishnu Upadhyay



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!