Why can a list in Python be used with the increment assignment operator and a string?

Question:

This isn’t so much an "I can’t get something to work" question as an, "I don’t understand what’s going on under the hood," question.

I’m learning Python and found that a list can use the increment augmented assignment operator with a string. Example:

    listvar = []
    listvar += 'asdf'

will result in listvar being

['a', 's', 'd', 'f']

Like it iterated over it and appended each element, while doing it with

listvar = listvar + 'asdf'

gives an expected error.

I read that the increment augmented assignment operator keeps a new object from being created with mutable objects, versus self=self+thing, and I noticed the working example gives an error for any object that isn’t iterable (e.g. an integer), but that’s where my understanding of differences ends.

What is happening when the augmented assignment operator is used in this context?

Python version is 3.9 if that matters.

edit: Tim thoroughly answered my question, but just in case anyone else comes along with a similar question, the accepted answer to this question about differences between .append() and .extend() also adds more details.

Asked By: Morgan

||

Answers:

list += x is basically the same as list.extend(x). It expects to receive a sequence, not a single item. You have given it a sequence, but when a string is treated as a sequence, it is a series of one-character substrings.

To add a single item, you need to use

listvar.append('asdf')
Answered By: Tim Roberts
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.