>>> 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
?
An augmented assignment is generally used to replace a statement where an operator takes a variable as one of its arguments and then assigns the result back to the same variable. A simple example is x += 1 which is expanded to x = x + (1) .
Any of the operators can be combined with assignment. The means that += , -= , *= , /= , //= , %= , **= , >>= , <<= , &= , ^= , and |= are all assignment operators.
Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With