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?
The + operator concatenates lists while the += operator extends a list with an iterable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With