>>> a = [1,2]
>>> a = a + "ali"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
For list data type use the .append method:
>>> a = [1,2]
>>> a.append("ali")
>>> a
[1, 2, 'ali']
The String in Python is defined as a series of characters in a row. So, these "characters" are added to the "list" type as the characters, not as "String". When you want use the += adding operator for the list type, you must specify the type of the added variable or value using square brackets:
>>> a = [1,2]
>>> a += ["ali"]
>>> a
[1, 2, 'ali']
>>> a += ["foo",3,"bar"]
>>> a
[1, 2, 'ali', 'foo', 3, 'bar']
i += 1andi = i + 1is not the same. The former modifies existing objectiwhereas the latter creates a new object. Try alsoa=[]; b=a; a+=[1]- it modifies bothaandb, whereasa = a + [1]modifies onlya.i). For built-in immutable objects, likeintandstr, they will probably do the same, because there is no way to modify the object. For mutable objects I would expect that they are different. That still does not explain why one accepts strings whereas the other does not, but I cannot give you a better answer for that part. To me it actually makes sense, but it could have been implemented differently.__iadd__and__add__both return objects.list.__iadd__returns itself whileint.__iadd__returns a new object. So,x = 1;x += 1creates a new object. The objects themselves decide what they should do.