How can I get the concatenation of two lists in Python without modifying either one?
In Python, the only way I can find to concatenate two lists is using list.extend()
, which modifies the first list. Is there any concatenation function that returns its result without modifying the arguments?
How can I implement concat lists with Python without changing the original lists?
The + operator allows you to concatenate two lists and return a new list without modifying the original ones.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(result) # Output: [1, 2, 3, 4, 5, 6]
You can use itertools.chain() to concatenate multiple lists. This function does not modify the original lists and returns an iterable, which can be converted to a list.
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list(itertools.chain(list1, list2))
print(result) # Output: [1, 2, 3, 4, 5, 6]
Python allows unpacking lists in function calls. This can also be used to concatenate two lists.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = [*list1, *list2]
print(result) # Output: [1, 2, 3, 4, 5, 6]