Select Page

We frequently come across situations where we need to add together two Python lists. We do have a couple of syntax options available to us as developers and they do, of course, have their tradeoffs. There isn’t necessarily one “right” answer for all situations. Let’s look at the options.

Let’s assume that we have two lists, a and b.

The simplest way to concatenate the lists is to use the + operator:

In this case, we have combined two lists, without changing them, and created now a third list (that is then assigned to c). So, we have three separate lists in memory.

In a simple case, like this example, that may not be a big deal. However, if your lists are very large then you may be consuming a lot of memory.

So, what to do in order not to use excess memory? We can modify a list in place so that we do not create a third list. We can accomplish that in two different ways:

The alternative syntax, with the same effect, is to use the += operator:

In either syntactical case, a.extend(b) or a += b, we are modifying a in place and adding each of the elements from b to the end of a. The key factor is that this technique does not create a third list. So we have some improvement in terms of memory efficiency.

A word of caution

There is another list method that seems like it might be helpful: list.append(). This method is significantly different because it will add a list as a single element into another list. The techniques above, in contrast, add the elements from one list into another list.

Share This