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. One way is to use the + operator to create a new list that is the concatenation of the two lists. For example:

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

Watch a course Python - The Practical Guide

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.

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.

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]