on a list +=
is the same as extend
. The argument is seen as an iterable. So it iterates on the string and adds it. But it's not correct in the general case, for instance a string with length > 1.
>>> lst = []
>>> lst += "ab"
>>> lst
['a', 'b'] # not what is expected probably
or adding an integer
>>> lst += 0
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not iterable
On the other hand, in lst + <right term>
, the right term is supposed to be a list. Even a tuple
would end up with an error.
In your case, the best solution is
lst += ['a']
or
lst.append('a')
which avoids creating a list just to add it to the first one.
As a side note,
lst = lst + other_list
is different from
lst += other_list
as it reassigns lst
name on a copy of the old list with added other_list
.
- Better be aware of that if some other variable is still referencing the old
lst
- Plus the performance suffers from the copy of the old contents.