How do I concatenate two lists in Python?
|In this Python example we will discuss some to concatenate two lists in Python.
Some of the topics which will be helpful for understanding the program implementation better are:
1. Using the +
operator
One way to concatenate two lists in Python is to use the +
operator. This operator combines the two lists into a new list that contains all the elements from both lists.
Here’s the code:
cars1 = ['Toyota', 'Honda', 'Nissan'] cars2 = ['BMW', 'Mercedes', 'Audi'] all_cars = cars1 + cars2 print(all_cars)
Output ['Toyota', 'Honda', 'Nissan', 'BMW', 'Mercedes', 'Audi']
2. Using the extend() method
extend()
method adds all the elements from one list to another list. It modifies the original list and does not create a new list.
Here’s the code
cars1 = ['Toyota', 'Honda', 'Nissan'] cars2 = ['BMW', 'Mercedes', 'Audi'] cars1.extend(cars2) print(cars1)
Output ['Toyota', 'Honda', 'Nissan', 'BMW', 'Mercedes', 'Audi']
3. Using the *
operator
The *
operator creates a new list that contains multiple copies of the original list.
Here’s the code
cars1 = ['Toyota', 'Honda', 'Nissan'] cars2 = ['BMW', 'Mercedes', 'Audi'] all_cars = cars1 * 2 + cars2 * 3 print(all_cars)
Output ['Toyota', 'Honda', 'Nissan', 'Toyota', 'Honda', 'Nissan', 'BMW', 'Mercedes', 'Audi', 'BMW', 'Mercedes', 'Audi', 'BMW', 'Mercedes', 'Audi']
4. Conclusion
In this Python example, we discussed how to concatenate two lists using the +
operator, the extend()
method, or the *
operator.
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?