Creating a new list that has two already defined variables
You can create a new list by combining two already defined variables using the +
operator or the extend()
method.
Here's an example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = list1 + list2
print(new_list) # Output: [1, 2, 3, 4, 5, 6]
Alternatively, you can use the extend()
method:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
Note that the extend()
method modifies the original list (list1
), whereas the +
operator creates a new list.
You can also use the concat()
method from the itertools
module:
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = list(itertools.concat(list1, list2))
print(new_list) # Output: [1, 2, 3, 4, 5, 6]
However, the concat()
method is not a built-in method and requires importing the itertools
module. The +
operator and extend()
method are more commonly used and convenient ways to combine lists.