Adding a string to a list using augmented assignment
>>> b = []
>>> c = '1234'
>>> b += c
>>> b
['1', '2', '3', '4']
>>>
What is happening here? This should not work, right? Or am I missing something obvious?
>>> b = []
>>> c = '1234'
>>> b + c
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
b + c
TypeError: can only concatenate list (not "str") to list
>>>
Then a += b
is not always equivalent to a = a + b
?
Strings are iterable: the elements are the string's characters. When you add an iterable to a list, the iterable's elements get appended to the list.
Either of the following will do what you're expecting (i.e. append the string, not extend the list with the string's characters):
b += [c]
or
b.append(c)
The +=
operator extends a list instead of appending to it:
>>> b = []
>>> c = "1234"
>>> b.append(c)
>>> b
['1234']
>>> b.extend(c)
>>> b
['1234', '1', '2', '3', '4']
>>> b += c
>>> b
['1234', '1', '2', '3', '4', '1', '2', '3', '4']
>>> b += [c]
>>> b
['1234', '1', '2', '3', '4', '1', '2', '3', '4', '1234']
This is an answer not to the original question (which I think has been adequately answered), but to the numerous questions that have been asked in the comments about the semantics of augmented assignment (+=
and similar operations).
In a nutshell: Augmented assignment works differently for mutable types than for immutable ones.
str
, tuple
, and the numeric types, among others, are immutable. The contents of a tuple cannot be changed once it has been created, so you get this behavior:
>>> a = (1, 2)
>>> b = a
>>> a += (3, 4)
>>> a
(1, 2, 3, 4)
>>> b
(1, 2)
str
has the same semantics. Basically, a += b
is equivalent to a = a + b
if a
is immutable.
Most other types, including list
, are mutable. A list's contents can be changed in place, and augmented assignment does exactly that. Hence:
>>> a = [1, 2]
>>> b = a
>>> a += [3, 4]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
Whereas if the third line were replaced with a = a + [3, 4]
, a new list would be created and b
would be [1, 2]
.
For a user-defined class, the semantics depend on how it was implemented, but this is how it's supposed to be done per PEP 203.
A string is a sequence of characters. The list operation +=
takes any sequence and appends each of the sequence's elements to the list.
(Actually +=
takes any iterable.)