Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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.

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading