Python provides several ways to join two or more lists.
Join lists using the arithmetic plus (+
) sign.
colors_list_1 = ["Red", "Blue"]
colors_list_2 = ["Green"]
colors_list_3 = colors_list_1 + colors_list_2
print(colors_list_3)
['Red', 'Blue', 'Green']
In the above example, we are joining two different lists using the plus (+
) sign and assigning those added lists to another list variable. Accordingly, both list items are present in the third join list.
Alternatively, you can join the list to iterate and append all items to another list.
colors_list_1 = ["Red", "Blue"]
colors_list_2 = ["Green"]
for color in colors_list_2:
colors_list_1.append(color)
print(colors_list_1)
['Red', 'Blue', 'Green']
In the above example, we are iterating a list using for loop and appending all items to another list.
Python provides an inbuilt extend()
function for joining lists.
colors_list_1 = ["Red", "Blue"]
colors_list_2 = ["Green"]
colors_list_1.extend(colors_list_2)
print(colors_list_1)
['Red', 'Blue', 'Green']
In the above example, we are joining two different lists using extend()
function.