How to Concatenate Two Lists in Python?

In programming, “concatenation” refers to the operation of linking things together in a series or chain. In the context of Python lists, concatenation refers to the act of joining two or more lists into a single list. Python offers multiple ways to perform this operation, with each method having its own use cases and implications. This article will explore the two primary ways of concatenating lists: using the + operator and the extend() method.

Of course! Let’s delve deeper into these two methods for concatenating lists in Python.

Using the + operator

The + operator, when applied to two lists, returns a new list that’s a combination of the elements from both lists. This operation doesn’t modify the original lists.

Pros:

  • Intuitive and easy to use.
  • Does not modify the original lists.

Cons:

  • It creates a new list, so if you’re working with large lists, this method may consume more memory because both the original lists and the new concatenated list exist simultaneously.

Example:

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']

combined_list = list1 + list2
print(combined_list)  # ['a', 'b', 'c', 'd', 'e', 'f']
print(list1)  # ['a', 'b', 'c']  # Unchanged
print(list2)  # ['d', 'e', 'f']  # Unchanged

Using the extend() method

The extend() method modifies the list it is called upon. It takes an iterable (like a list) as an argument and appends each of its items to the list.

Pros:

  • Doesn’t create a new list, so it’s more memory-efficient if the first list is already large.
  • Useful when you want to modify the original list.

Cons:

  • Modifies the original list. If you need to retain the original list, you’ll have to make a copy before using extend().

Example:

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']

list1.extend(list2)
print(list1)  # ['a', 'b', 'c', 'd', 'e', 'f']
print(list2)  # ['d', 'e', 'f']  # Unchanged

Additional Notes:

  1. When concatenating, ensure both variables are of type list. If one of them isn’t, you’d encounter a TypeError.

  2. If you frequently need to add items to the end of a list, consider using collections.deque which is designed to handle appends and pops from both ends in a faster manner than a regular list.

  3. If you’re looking to not just concatenate, but to merge multiple lists into one, the itertools.chain function might be of interest. It allows concatenating more than two lists (or iterables) at once:

import itertools

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

combined_list = list(itertools.chain(list1, list2, list3))
print(combined_list)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]