• Register

In this tutorial, we will discuss how to merge two lists in Python, and also we will learn all about the list in Python. So if you are new to Python coding then this tutorial for you.

We have created this list for those coders who are new to python. And this article divided into various steps so, you need to read the full tutorial till the end.

Step1: In this article, we will discuss about the list in Python. So list is a collection of items, lists are defined in Python by enclosing a comma-separated sequence of objects in square brackets “[ ] “” and we can see below:

Syntax with Example: 

 >>> a = ['Kodlogs', 'Github', 'Slack']
>>> print(a)
['Kodlogs', 'Github', 'Slack']

Step2: Now, It's time to merge two given lists and we will talk about how we can merge two lists. First of all, there are several ways to join, or concatenate, two or more lists in Python. So we will use every method one by one.

Step3: In this step, we will write our python code and solve this question with the helps of joining or concatenate.

Method 1: Joining or Concatenate two list

Code: 

listA = ['Delhi', 'Punjab', 'Uttarakhand']
listB = ['44', '31', '01']
listC = listA + listB
print(listC)

Output: 

['Delhi', 'Punjab', 'Uttarakhand', '44', '31', '01']

Method2: In this method, we will join two lists by appending all the items from the list into the list, one by one but here we need to loop we because we will append every item.

Code: 

listA = [‘Noida’, ‘Delhi’, ‘Banglore’]
listB = [‘14’, ‘55’, ‘91’]

for x in listB:
    listA.append(x)
print(listA)

Output: 

['Delhi', 'Punjab', 'Uttarakhand', '44', '31', '01']

Method3: In method3 we can use the extend() method, which purpose is to add elements from one list to another list

Code: 

listA = [‘Noida’, ‘Delhi’, ‘Banglore’]
listB = [‘14’, ‘55’, ‘91’]

listA.extend(listB)
print(listA)

Output: 

['Delhi', 'Punjab', 'Uttarakhand', '44', '31', '01']

 

190 points
4