How to concatenate two lists
How to concatenate two lists.
Here's a detailed step-by-step tutorial on how to concatenate two lists in Python:
Step 1: Create the initial lists
- Start by creating two lists that you want to concatenate. These lists can contain any type of elements such as integers, strings, or even other lists.
Step 2: Use the '+' operator
- The easiest way to concatenate two lists in Python is by using the '+' operator. This operator is overloaded for lists and can be used to combine them into a new list.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list)
Output:
[1, 2, 3, 4, 5, 6]
Step 3: Use the extend() method
- Another way to concatenate two lists is by using the
extend()method. This method modifies the original list by adding the elements from another list at the end.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
Output:
[1, 2, 3, 4, 5, 6]
Step 4: Use the append() method in a loop
- If you want to concatenate multiple lists, you can use the
append()method in a loop to add each element from one list to another.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
concatenated_list = []
for lst in [list1, list2, list3]:
concatenated_list.extend(lst)
print(concatenated_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Step 5: Use the itertools.chain() function
- If you prefer using a built-in function, you can use the
itertools.chain()function to concatenate multiple lists. This function takes multiple iterables as arguments and returns a single iterable.
Example:
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
concatenated_list = list(itertools.chain(list1, list2, list3))
print(concatenated_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
That's it! You now know several ways to concatenate two or more lists in Python. Choose the method that best suits your needs and enjoy working with concatenated lists.