0

Declaration

lst = []

What is the difference between these two lines in python why first line is working another is not

lst += 'a' # this line is working
lst = lst + 'a' # but this line is showing error 'can only concatenate list (not "str") to list'

Not understanding why this two statements are giving different results

  • Does this answer your question? [+ and += operators are different?](https://stackoverflow.com/questions/2027284/and-operators-are-different) – Mechanic Pig Jan 19 '23 at 15:32
  • My reputation is too low to comment, but have a look at [this](https://stackoverflow.com/questions/15376509/when-is-i-x-different-from-i-i-x-in-python) question: – Victor Jan 19 '23 at 15:39

1 Answers1

1

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.
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219