zaro

How to Concatenate a List in Python?

Published in Python Lists 2 mins read

To concatenate lists in Python, you can use the + operator, the extend() method, or the itertools.chain() function. Here's a breakdown of each method:

1. Using the + Operator

The + operator creates a new list containing the elements of both lists.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list)  # Output: [1, 2, 3, 4, 5, 6]
  • Pros: Simple and easy to read.
  • Cons: Creates a new list, which can be inefficient for large lists as it involves copying elements.

2. Using the extend() Method

The extend() method adds the elements of one list to the end of another list (modifies the original list in-place).

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)  # Output: [1, 2, 3, 4, 5, 6]
  • Pros: Modifies the original list directly, potentially more efficient than using + for large lists.
  • Cons: Modifies the original list, which might not be desirable in all cases.

3. Using itertools.chain()

The itertools.chain() function from the itertools module creates an iterator that returns elements from the input iterables sequentially. This is memory-efficient, especially for concatenating a large number of lists or very large lists, as it doesn't create a new list in memory all at once.

import itertools

list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list(itertools.chain(list1, list2)) # needs to be cast to a list
print(concatenated_list)  # Output: [1, 2, 3, 4, 5, 6]

#Concatenating multiple lists:
list3 = [7, 8, 9]
concatenated_list = list(itertools.chain(list1, list2, list3))
print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • Pros: Memory-efficient, especially for large lists or many lists. Suitable for lazy evaluation.
  • Cons: Requires importing the itertools module. Returns an iterator, so you often need to convert it to a list using list(). Can be slightly less readable than the + operator for simple cases.

Summary Table

Method Description Pros Cons
+ Operator Creates a new list containing elements from both lists. Simple, easy to read. Creates a new list (less efficient for large lists).
extend() Method Adds elements of one list to the end of another (modifies the original). Modifies in-place (potentially more efficient for large lists). Modifies the original list.
itertools.chain() Function Creates an iterator that yields elements sequentially from input iterables. Memory-efficient (especially for large lists or many lists). Requires import, returns an iterator. Less readable for simple cases.

Choose the method that best suits your needs based on the size of your lists, memory constraints, and whether you want to modify the original lists.