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)

30th Jul 2019, 5:31 AM
Дмитрий Кудря
Дмитрий Кудря - avatar
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]
30th Jul 2019, 9:06 AM
HonFu
HonFu - avatar
+ 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😅
30th Jul 2019, 6:17 AM
Trigger
Trigger - avatar
30th Jul 2019, 5:50 AM
Trigger
Trigger - avatar
+ 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"
30th Jul 2019, 7:41 AM
Seb TheS
Seb TheS - avatar
0
The question is " why (a +=" abc" working, but a = a+"abc" not working)?
30th Jul 2019, 6:09 AM
Дмитрий Кудря
Дмитрий Кудря - avatar