+ 1

Adding chars to list by different methods

Hi, can anyone please explain why these two operations (see code snippet) don't behave the same way? Doing (a=[] ; a+="string") builds a list of chars, but what seems like it ought to be equivalent (b=[] ; b=b+"string") throws an error...? https://code.sololearn.com/cYMU5cuyZ8JG/?ref=app

3rd Oct 2017, 12:20 PM
Erik
2 ответов
+ 2
The statement a += "string" is NOT equivalent to a = a + "string" Because Python is strongly typed, you cannot use the + operator with a list and a str. However, a str CAN be considered as a list of unitary (as in, len == 1) str, thus += does an implicit conversion : the former is equivalent to : a = a + list("string")
3rd Oct 2017, 4:28 PM
Amaras A
Amaras A - avatar
+ 1
Hi Amaras, thanks for the reply. I guess I knew all that already...should perhaps have clarified that the surprising part is that my first example does NOT throw an error; my second example, which gives an error, is what I would have expected. In any case, still seems strange that the "+=" shorthand operator actually gives a different result than saying "a=a+..."
5th Oct 2017, 2:26 AM
Erik