1

OK, so still on my path to learning Python where I encountered a weird behavior. Here's a snippet of code:

c1 = [2, 5, 8, 9]
c2 = 'hello'

Now, when I try to add the two lists with a c1 = c1 + c2, I get an error, but c1 += c2 works fine as expected. Aren't the two exacty the same expressions?

  • 3
    " Aren't the two exacty the same expressions?" no, no they aren't. `c1 + c2` essentially will evaluate to `c1.__add__(c2)`. On the other hand, `c1 += c2` is equivalent to `c1 = c1.__iadd__(c2)`. It is an "augmented assignment" operator. These were added *specifically* to work differently than their corresponding non assignment operator, `(+= vs +)` by working *in-place*. For lists specifically, it is going to be equivalent to `c1.extend(c2)` – juanpa.arrivillaga Oct 18 '21 at 20:22

0 Answers0