Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does augmented assignment behave differently when adding a string to a list [duplicate]

I am in a very interesting situation and I am so surprised. actually I thought both i += 1 and i = i + 1 are same. but it'is not same in here;

a = [1,2]
a += "ali"

and output is [1,2,"a","l","i"]

but if I write like that;

a = [1,2]
a = a + "ali"

it doesn't work.

I am really confused about this. are they different?

like image 319
Njx Avatar asked May 23 '18 19:05

Njx


1 Answers

Short answer

The + operator concatenates lists while the += operator extends a list with an iterable.

Long answer

The + operator concatenate lists to return a new list...

l1 = l2 = []
l1 = l1 + [1]

l1 # [1]
l2 # []

... while the += operator extends a list, by mutating it.

l1 = l2 = []
l1 += [1]

l1 # [1]
l2 # [1]

What allows different behaviours is that + calls the __add__ method while += calls the __iadd__ method.

In your example, you provided a string to the __iadd__ method, which is equivalent to doing l.extend('ali'). In particular, you can extend a list with any iterable, but concatenation arguments must both be lists.

Although, there is a slight difference between list.__iadd__ and list.extend. The former returns the mutated list, while the later does not.

like image 88
Olivier Melançon Avatar answered Nov 06 '22 09:11

Olivier Melançon