Python: ADD (+) vs. INPLACE_ADD (+=) vs. extend() for LIST

Today's Python series by Jake Gober led me to consider why there's difference between concatenate (+) two lists to the same variable and using the extend() function on the list.

The answer is ADD (+) creates a new list, I supposed even though the variable name is the same, it is still going to be a new list, so the list that was earlier assigned to the dictionary would not be affected. While += works on the same object, as does extend() rather than creating a new one, so there's no need to update the dictionary after the change in list. Therefore, ADD, by creating a new list, makes the operation slower, some clocked it 3 times slower than the other two, see chart below.

I had to google it for a while because most results are only talking about the difference in runtime. But this site hits the mark. I've pasted the answer in the comment in case the site expires. They have a nice chart for runtime as well:

In conclusion: It seems that Python is using some kind of pointers in its object creation, but I am not certain and I fear it would take up more time and energy than I wanted to explore into it, so I'll leave it as a question for now. This is good enough.

This entry was posted in Questions, Technical. Bookmark the permalink.

One Response to Python: ADD (+) vs. INPLACE_ADD (+=) vs. extend() for LIST

  1. timlyg says:

    Source: https://blog.finxter.com/python-list-concatenation-add-vs-inplace-add-vs-extend/
    A wildly popular operation you’ll find in any (non-trivial) code base is to concatenate lists—but there are multiple methods to accomplish this. Master coders will always choose the right method for the right problem.

    This tutorial shows you the difference between three methods to concatenate lists:

    Concatenate two lists with the + operator. For example, the expression [1, 2, 3] + [4, 5] results in a new list [1, 2, 3, 4, 5]. More here.
    Concatenate two lists with the += operator. This operation is inplace which means that you don’t create a new list and the result of the expression lst += [4, 5] is to add the elements on the right to the existing list object lst. More here.
    Concatenate two lists with the extend() method of Python lists. Like +=, this method modifies an existing list in place. So the result of lst.extend([4, 5]) adds the elements 4 and 5 to the list lst. More here.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.