1

code 1

display = []
for _ in range(2):
    display += "_"

print(display)

concole output = [" _ ", " _ "]


code 2

dis = []
dis = dis + "_"

print(dis) 

output on the console: can only concatenate a string to list

In the first code, I don't understand how concatenation yields the output results. But in the second code when the same thing is performed with no loop it gives the error as mentioned above.

aneroid
  • 12,983
  • 3
  • 36
  • 66
  • 3
    Does this answer your question? [When is "i += x" different from "i = i + x" in Python?](https://stackoverflow.com/questions/15376509/when-is-i-x-different-from-i-i-x-in-python) – Ruli Dec 24 '20 at 15:19

2 Answers2

2
a = a + b

and

a += b

are not equivalent in the general case in Python. In particular, the mutable types implement the += operation as a mutation (the type of a won't change) while + will always create a new object (this has greater restrictions wrt the compatibility of the types of the two operands because a decision needs to be made what type the result should be). For lists

lst += x

corresponds to

lst.extend(x)

where extend can take as an argument any iterable (including strings). This becomes clearer if you try it with a longer string:

lst = []
lst += "abc"
lst
# ['a', 'b', 'c']
user2390182
  • 72,016
  • 6
  • 67
  • 89
-1

You used display += "_" in first code. In second code, you used dis = dis + "_". If you used display = display + "_" in first code, you will get the same error. Use dis += "_" in second code.

HRS0986
  • 23
  • 4