Hi there,
I used list += item to add student in the poetry class, but they broke down as characters rather than original elements of a name. But when I used .append() it worked again. What’s the reason? Thanks a lot!
A list can be concatenated with another list. It cannot, however, be concatenated with a single value that is not constructed as a list object.
>>> a = [2, 5, 9, 12]
>>> a += 18
Traceback (most recent call last):
File "<pyshell#93>", line 1, in <module>
a += 18
TypeError: 'int' object is not iterable
>>>
But, a sequence is iterable, so,
>>> a += 18, 25
>>> a
[2, 5, 9, 18, 25]
>>>
If we study the code in the screen-grab, we see a list being concatenated with a string (the popped object). The primitive cannot be concatenated; however, Python defines a string as iterable, and therefore assigns it as a sequence, hence they are inserted as single character string objects.
Edited: 2020/01/30
We can concatenate a single character string value; it’s a sequence with length 1.