Home » Python program to merge or concatenate two lists

Python program to merge or concatenate two lists

Python program to merge or concatenate two lists

Hello everyone, welcome back to Programming In Python. Here in this post am going to tell you how to concatenate or merge lists. We can simply add any number of lists by just adding them like a normal add operation with + operator.

You can watch this video on Youtube here

Program on GitHub

Master the basics of data analysis in Python. Expand your skillset by learning scientific computing with numpy.

Take the course on Introduction to Python on DataCamp here https://bit.ly/datacamp-intro-to-python

Add, concatenate, or merge lists – Code Visualization

Task:

To merge/concatenate/add lists.

Approach:

  • Read the input number asking for the length of the list using input() or raw_input().
  • Initialize an empty list lst = [].
  • Read each number using a for loop.
  • In the for loop append each number to the list.
  • Repeat the above 4 points for the second list lst2[] as well.
  • Now add the two lists lst + lst2
  • Print the resultant list of the above operation.

Program on GitHub

Program:

__author__ = 'Avinash'

lst = []
num = int(input('How many numbers in list 1: '))
for n in range(num):
    numbers = int(input('Enter number '))
    lst.append(numbers)

lst2 = []
num1 = int(input('How many numbers in list 2: '))
for n in range(num1):
    numbers = int(input('Enter number '))
    lst2.append(numbers)

merged_lst = lst + lst2

print("Merged List with elements from both lists:", merged_lst)

Output:

Python program to merge or concatenate lists
Python program to merge two lists

That is it for the post. It is that simple to add multiple lists into a single list, it is just like adding 2 numbers with a + operator, we add 2 lists with a + operator here, like lst1 + lst2

Program on GitHub

For more programs on Lists, check some of the posts below.

Course Suggestion

Want to learn Python with strong fundamentals? If yes, I strongly suggest you take the course below.
Course: Fundamentals of Programming in Python

Online Python Compiler

Leave a Reply

Your email address will not be published. Required fields are marked *