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
Of course! Let’s delve deeper into these two methods for concatenating lists in Python.
Using the + operator
+ 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.
- Intuitive and easy to use.
- Does not modify the original lists.
- 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.
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
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.
- 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.
- Modifies the original list. If you need to retain the original list, you’ll have to make a copy before using
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
When concatenating, ensure both variables are of type
list. If one of them isn’t, you’d encounter a TypeError.
If you frequently need to add items to the end of a list, consider using
collections.dequewhich is designed to handle appends and pops from both ends in a faster manner than a regular list.
If you’re looking to not just concatenate, but to merge multiple lists into one, the
itertools.chainfunction 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]