Python - Join Lists
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the +
operator.
Example
Join two list:
class="pythoncolor" style="color:black">class="pythonnumbercolor" style="color:red">
list1 = [class="pythonstringcolor" style="color:brown">"a", class="pythonstringcolor" style="color:brown">"b", class="pythonstringcolor" style="color:brown">"c"]
list2 = [class="pythonnumbercolor" style="color:red">1, class="pythonnumbercolor" style="color:red">2, class="pythonnumbercolor" style="color:red">3]
list3 = list1 + list2
class="pythonkeywordcolor" style="color:mediumblue">print(list3)class="pythonnumbercolor" style="color:red">
Try it Yourself »
Another way to join two lists is by appending all the items from list2 into list1, one by one:
Example
Append list2 into list1:
class="pythoncolor" style="color:black">class="pythonnumbercolor" style="color:red">
list1 = [class="pythonstringcolor" style="color:brown">"a", class="pythonstringcolor" style="color:brown">"b" , class="pythonstringcolor" style="color:brown">"c"]
list2 = [class="pythonnumbercolor" style="color:red">1, class="pythonnumbercolor" style="color:red">2, class="pythonnumbercolor" style="color:red">3]
class="pythonkeywordcolor" style="color:mediumblue">for x class="pythonkeywordcolor" style="color:mediumblue">in list2:
list1.append(x)
class="pythonkeywordcolor" style="color:mediumblue">print(list1)class="pythonnumbercolor" style="color:red">
Try it Yourself »
Or you can use the extend()
method, which purpose is to add elements from one list to another list:
Example
Use the extend()
method to add list2 at the end of list1:
class="pythoncolor" style="color:black">class="pythonnumbercolor" style="color:red">
list1 = [class="pythonstringcolor" style="color:brown">"a", class="pythonstringcolor" style="color:brown">"b" , class="pythonstringcolor" style="color:brown">"c"]
list2 = [class="pythonnumbercolor" style="color:red">1, class="pythonnumbercolor" style="color:red">2, class="pythonnumbercolor" style="color:red">3]
list1.extend(list2)
class="pythonkeywordcolor" style="color:mediumblue">print(list1)class="pythonnumbercolor" style="color:red">
Try it Yourself »