The Power of List Comprehension and the ‘+’ Operator in Python

In this article, you’ll learn how to combine or merge two lists in Python. You will also see that there are alternative ways to do it such as using extend() and + operator, along with list comprehensi …

Updated November 15, 2023

In this article, you’ll learn how to combine or merge two lists in Python. You will also see that there are alternative ways to do it such as using extend() and + operator, along with list comprehensions and other built-in functions.

To begin with, we first need to create the two lists. Let’s consider two lists:

list1 = [1,2,3]
list2 = [4,5,6]

Now, let’s merge these two lists using ‘+’ operator. This is quite straightforward and can be done as follows:

merged_list = list1 + list2
print(merged_list)  # Output: [1,2,3,4,5,6]

This will concatenate or merge the two lists together into one. However, a problem arises when we try to combine larger lists. If the lists are very large, it may consume significant memory and time. There’s an alternative way using extend() method:

list1 = [1,2,3]
list2 = [4,5,6]

list1.extend(list2)  # This adds list2 to the end of list1
print(list1)  # Output: [1,2,3,4,5,6]

The extend() method doesn’t return a new list, but instead updates the original list that it is called on.

Now let’s use list comprehension to merge two lists:

list1 = [1,2,3]
list2 = [4,5,6]

merged_list = [i for i in list1] + [j for j in list2]
print(merged_list)  # Output: [1,2,3,4,5,6]

Here, we are using list comprehension to iterate over the elements of both lists and create a new combined list.

Lastly, let’s illustrate combining two lists using Python’s built-in ‘zip_longest()’ function from itertools module:

from itertools import zip_longest
list1 = [1,2,3]
list2 = [4,5,6]

merged_list = [x for pair in zip_longest(list1, list2) for x in pair if x is not None]
print(merged_list)  # Output: [1,2,3,4,5,6]

The ‘zip_longest()’ function takes two lists and makes pairs of corresponding elements. If one list is longer than the other, it will append a fill value (None by default) to the end of the shorter list until the lengths are equal. The code then flattens this paired result into a single list.

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!