This article is a quick guide on how you can concatenate two or more lists into one single list in Python. There are several methods for list concatenation.
Table of Contents
Python List Concatenation Using +
Operator
In Python, one can simply use the +
operator to concatenate any number of lists together as demonstrated below. The code for the same is written below and then the output is displayed in the screenshot.
Example Code.
1 2 3 4 |
list1 = [1,2,3,4,5,6,7] list2 = [8,9,10,11,12,13,14] combinedList = list1 + list2 print(combinedList) |
Output.
You can also use the +=
operator for appending a new list to an existing list as expressed in the code given below.
Code.
1 2 3 4 |
list1 = [1,2,3,4,5,6,7] list2 = [5,6,7,8,9,10,11] list1 += list2 print(list1) |
Output.
Concat Lists Using List Literal (Only For Python 3.5 or higher)
In Python version 3.5 or higher, you can also concatenate lists using list literal as demonstrated in the example code given below.
Example Code.
1 2 3 4 |
list1 = [1,2,3,4,5,6,7] list2 = [8,9,10,11,12,13,14] combinedList = [*list1,*list2] print(combinedList) |
Output.
List Concatenation In Python For A Unique List
This is a very useful thing for Python List Concatenation. There might be some of the same values in two different lists that you wanted to merge or concatenate. But in the resultant concatenated list you might only require the unique merged values out of both lists. Then this solution that uses the set function is going to help you.
In the following code, there are two lists. Both of these lists have some common values. In the merged or concatenated lists we do not want the values to be repeated. So, here we wanted to have concatenated lists with unique values.
Code.
1 2 3 4 |
list1 = [1,2,3,4,5,6,7] list2 = [5,6,7,8,9,10,11] combinedUniqueList = list(set(list1 + list2)) print(combinedUniqueList) |
Output.
Merging Python Lists Using Extend Function
This is another great way to extend or merge Python lists and can help in several different use cases.
Code.
1 2 3 4 |
list1 = [1,2,3,4,5,6,7] list2 = [5,6,7,8,9,10,11] list1.extend(list2) print(list1) |
Output.
Related Articles.
- How To Append To An Array in Javascript?
- Find Size of a List In Python
- How To Get Substring Of A String In Python?
There are numerous other methods and tricks to concatenate or merge lists in python. If you know any better and easy way, let our visitors know in the comments section.
I hope as a beginner, you found this article useful. If so, do share it with others who might get benefits from this article as well. Feel free to ask any kind of questions related to this article in the comments section.
Also, don’t forget to Subscribe to WTMatter!