Skip to main content

How to concatenate two lists in Python

How to concatenate two lists in Python.

Here's a step-by-step tutorial on how to concatenate two lists in Python:

1: Create two lists

First, you need to create two lists that you want to concatenate. Let's call them list1 and list2. You can assign values to these lists using square brackets [] and separating the elements with commas.

list1 = [1, 2, 3]
list2 = [4, 5, 6]

2: Using the '+' operator

In Python, you can concatenate two lists using the + operator. Simply use the + operator between the two lists you want to concatenate.

concatenated_list = list1 + list2

3: Printing the concatenated list

You can print the concatenated list using the print() function.

print(concatenated_list)

4: Using the extend() method

Another way to concatenate two lists is by using the extend() method. This method adds all the elements from one list to the end of another list.

list1.extend(list2)

5: Printing the concatenated list

Again, you can print the concatenated list using the print() function.

print(list1)

6: Using the append() method in a loop

If you have multiple lists that you want to concatenate, you can use a loop and the append() method to achieve this. First, create an empty list called concatenated_list to store the final result. Then, iterate over each list using a loop and append its elements to the concatenated_list.

concatenated_list = []
lists = [list1, list2] # List of lists to concatenate

for l in lists:
concatenated_list.extend(l)

7: Printing the concatenated list

Finally, you can print the concatenated list using the print() function.

print(concatenated_list)

That's it! You now know how to concatenate two lists in Python using different methods. Feel free to choose the method that suits your requirements best.