Difference between + and += operator in Python

What is the difference between + and += operators in python lists?
ie:lst=lst+xy vs lst+=“xy” .

While using with integers, both + and += work somewhat similarly, so I expected both to be producing an error when used with lists; but the results were different when I tried it out!
Only + operator produced an error but += operator added elements by the end of the list

Someone told me that the + operator in lists is called concatenation while += is for the addition of elements.

I don’t understand how & why this happens, I will be thankful if someone could help me.

Mutable python objects may handle in-place addition differently from simple addition.

For lists, in-place addition is basically equivalent to the extend() method. This method does not require a list but accepts any iterable. For your example, the string is iterated and each of the characters within is added as a new element of the existing list.

extend(self, iterable, /)
    Extend list by appending elements from the iterable.

Thanks for trying to help :smiley::smiley:
My confusion is both + and += works somewhat similarly in integers.
but + is producing error in lists while += is acting like .extend() function
Why is that, If += and + have different functionality, how do they differ ?!?!

Hi Hari,

The rule for augmented assignment operators such as += is that, like

other operators, they call a special “dunder” (double-underscore) method

to allow classes to customise what the operation does.

If the special dunder operation doesn’t exist, then the augmented

assignment falls back on the ordinary operator.

So the operation:

obj += x

turns into something like this in the interpreter:

  1. Does obj have the special method __iadd__?

  2. If so, then run obj = obj.__iadd__(x).

  3. If not, then run obj = obj + x.

For integers, there is no special __iadd__ method, and so the +=

operation is just syntactic sugar for n = n + m. Same for strings.

But lists do define a special __iadd__ method, making it an inplace

concatenation.

For lists, + does list concatenation:

mylist + x

requires x to be a list, and it returns a new list formed by

concatenating all the items of mylist and the items of x.

mylist = [10, 20]

new = mylist + [30, 40]  # Can only add list to list.

print(new)

prints a new list, [10, 20, 30, 40] while leaving the original mylist

untouched.

But augmented assignment += does in-place concatenation:

mylist += x

and x can be any sequence, not just a list, and it concatenates the

items of x to mylist in-place. It does not create a new list.

mylist = [10, 20]

mylist += [30, 40]  # mylist is now [10, 20, 30, 40]

mylist += (50, 60)  # tuples are okay, not just lists

mylist += "xyz"  # strings are sequences too!

print(mylist)

will print [10, 20, 30, 40, 50, 60, 'x', 'y', 'z'].

So + and += for lists are still concatenation, just slightly

different versions:

  • + is list-to-list concatenation, and returns a new list

  • += concatenates the items of any sequence or iterator to the

    existing list, in-place.

3 Likes

Wow! I never knew about this
Thanks a lot for teaching me :smiley::smiley:

Convert String to Boolean in Python - LambdaTest Community - This discussion on converting strings to booleans in Python is quite insightful, especially for those new to the language. Found it really helpful!

The how part is easy to answer. The plus operator and plus-equal operator for lists work like this:

def plus(somelist, seq):
    """Return a new list containing elements from both inputs."""
    if not isinstance(seq, list):
        raise TypeError(f'can only concatenate list (not "{type(seq).__name__}") to list')
    result = somelist.copy()
    for element in seq:
        result.append(element)
    return result

def plus_equal(somelist, iterable):
    """Extend a list with elements from an iterable."""
    for element in iterable:
        somelist.append(element)
    return somelist

The first one creates a new list and leaves the input unchanged. Also, the first one only works with list inputs.

The second mutates in the input list in-place, accepts any iterable for the other input, and returns the mutated list.

The why part is more difficult to answer. One of Guido van Rossum’s talks said it was a design mistake for the plus-equal operator to accept any input iterable. However, it was too late to change the decision without breaking previously valid code. The concern was that some programmers presumed that plus_equal meant the same as list.append rather than list.extend. That led to bugs such as `s += “hello world” adding each character separately rather than adding a single string.

1 Like