0
results=[]
for x in range(5):
    results += '$' 
print(results)

output : ['$', '$', '$', '$', '$']

This code behaves differently from typical += operator. As you can see here it has generated a list with the $ string inside it.

It's not equal to what we think results = results + '$'. This code will throw you an error.

Can you describe what is going on this code?

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
ranga abi
  • 39
  • 1
  • 7
  • 2
    The output clearly shows what happens when you use `+=` with a list and a string... If you want a more detailed explanation, a quick search on google reveals [this](https://www.codecademy.com/forum_questions/559a2e9576b8fec400000392) – kenntnisse Apr 21 '22 at 03:26

1 Answers1

1

In lists, += is equivalent to .extend(). Since a string is an iterable, this works.

+ however is only defined to allow combining 2 lists together.

Bharel
  • 23,672
  • 5
  • 40
  • 80