Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 295
joaquin Avatar asked Nov 30 '11 08:11

joaquin


People also ask

What is an example of an augmented assignment operator?

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) .

Is %= an augmented assignment operator?

Any of the operators can be combined with assignment. The means that += , -= , *= , /= , //= , %= , **= , >>= , <<= , &= , ^= , and |= are all assignment operators.

What is an augmented assignment in Python?

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.


2 Answers

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)
like image 197
NPE Avatar answered Nov 01 '22 19:11

NPE


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']
like image 44
Tim Pietzcker Avatar answered Nov 01 '22 19:11

Tim Pietzcker