Creating a new list that has two already defined elements
You can create a new list by combining two existing lists using the +
operator or the extend()
method. Here are some examples:
Using the +
operator
list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = list1 + list2
print(new_list) # Output: [1, 2, 3, 4, 5, 6]
Using the extend()
method
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
Using list comprehension
list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = [x for x in list1 + list2]
print(new_list) # Output: [1, 2, 3, 4, 5, 6]
Note that the extend()
method modifies the original list, while the +
operator and list comprehension create a new list.