0

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.

Morgan
  • 3
  • 3
  • Further details, including performance implications, in [this question](https://stackoverflow.com/questions/725782/in-python-what-is-the-difference-between-append-and). – sj95126 Sep 25 '22 at 03:54

1 Answers1

0

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')
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • I poked around in the console and found that .extend() still preserves the object id#. Are there any appreciable differences between using += and .extend(), that is, situations where I might want one vs. the other with lists? – Morgan Sep 25 '22 at 03:48
  • None at all. It's likely that the implementation of `list.__iadd__` just calls `list.extend`. (Not literally, since the implementation is in C.) It comes down to personal preference. I've been using Python since before the augmented operators were added, so I always write `extend`. – Tim Roberts Sep 25 '22 at 03:50