W3docs

How can I get the concatenation of two lists in Python without modifying either one?

There are a few different ways to concatenate two lists in Python without modifying either one.

There are a few different ways to concatenate two lists in Python without modifying either one. One way is to use the + operator to create a new list that is the concatenation of the two lists. For example:

Using the + operator to concat two lists in Python

list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = list1 + list2
print(new_list)  # Output: [1, 2, 3, 4, 5, 6]

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

Another way to concatenate two lists is to use the extend() method of the first list, which adds the elements of the second list to the end of the first list. However, this method modifies the first list in place, so you will need to make a copy of the first list before calling extend() if you want to avoid modifying the original list.

Using the extend function to concat two lists in Python

list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = list1.copy()
new_list.extend(list2)
print(new_list)  # Output: [1, 2, 3, 4, 5, 6]

You can also use the itertools.chain() function from the itertools module to concatenate two lists without creating a new list. This function returns an iterator that yields the elements of the lists one after the other.

Using the itertools module to concat two lists in Python

import itertools

list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = list(itertools.chain(list1, list2))
print(new_list)  # Output: [1, 2, 3, 4, 5, 6]