0
Why a += "abc" not equal a = a + "abc"
a=[1,2,3] a+="abc" print(a) #[1, 2, 3, 'a' , 'b', 'c' ] why not [1,2,3,"abc"]? a.append("abc") print(a) #[1,2,3, 'a' , 'b', 'c', 'abc'] a=a+"abc" print (a) # give error int + str. Why? (a += b) != (a = a + b)
6 Answers
+ 3
+= works like list.extend:
The iterable you add, is 'unpacked'.
So if a is [],
a += 'ab' becomes ['a', 'b']
a += (5, 7) becomes [5, 7]
+ 2
Because (as I understand it), "+=" adds (inserts / grows / merges) a value to another value
a = a + "be" makes another list value, but sees you are trying to concatenate (sort of like a lego) two different data types
Best to use only "+=" and append() while working with lists
HonFu [#GoGetThatBugChamp!], can you give the correct reason? I dont think mine is adequate😅
+ 1
I hate that, it makes no sense.
But it's propably because string works much like a list, it's characters can be indexed and sliced.
With:
a += "abc"
a was changed to [1, 2, 3, 'a', 'b', 'c']
It is same than a + list("abc"), actually it starts to make sense.
With:
a += "abc"
The program knows, that the modified object is a list. Then it could automatically convert "abc" to list.
With:
a = a + "abc"
You would not know whether you want the result of a + "abc" to be a string or as a list, so it is safest to raise an error.
Would this also work?
x = 8
x += "5"
0
The question is " why (a +=" abc" working, but a = a+"abc" not working)?