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?
In python, since you can't declare static types, this behavior doesn't show up, but if you look at C++, if you declare
int a = 4
as an integer and then doa += 5.4
,a
will become9
, whereasa = a + 5.4
will break.The reason for this is that
a += b
anda = a + b
aren't the same. In python terms,a += b
is justa.__iadd__(b)
anda = a + b
isa = a.__add__(b)
, or if that doesn't exist,a = b.__radd__(a)
. You can't add lists and strings together using+
so the second code doesn't work, but+=
works because it automatically casts certain types to each other, namely converting iterables to each other. You cannot doa = []; a += ""
but you can do it vice-versa because you can convert the string to a list unambiguously usinglist("...")
.