You can combine or concatenate lists in a few ways, each suited to different needs. The two main methods for list concatenation are using the +
operator and the extend()
method.
+
OperatorThe +
operator allows you to concatenate two or more lists by creating a new list that contains elements from all the lists. This method does not modify the original lists, so you’ll end up with a new list that combines the contents of the existing ones.
# Example lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Concatenating using +
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
While using +
is quick and easy, it can be inefficient for large lists because it creates a new list and requires copying each element. This can be resource-intensive if done repeatedly in a loop.
extend()
MethodThe extend()
method adds all elements from another list to the end of the list on which it’s called. Unlike +
, extend()
modifies the original list directly instead of creating a new one, which can make it more memory-efficient for large lists.
# Example lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Extending list1 with elements of list2
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
extend()
is useful when you want to add elements to an existing list without creating a new list.
+
and extend()
+
when you need a new list and don’t want to alter the original lists.extend()
when you want to add elements directly to an existing list and avoid the memory overhead of creating a new list.You can concatenate lists using list comprehensions, especially if you need to filter or transform elements before combining.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = [x for x in list1] + [y for y in list2]
itertools.chain()
For very large lists, itertools.chain()
can concatenate lists without creating intermediate lists. This method is efficient for memory management in cases of extensive data processing.
from itertools import chain
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list(chain(list1, list2))
+
: Concatenates lists into a new list without modifying originals.extend()
: Adds elements of one list to another, modifying the existing list.itertools.chain()
: Efficiently concatenates large lists without intermediate copying.