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
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()
orraw_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:
__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:
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
For more programs on Lists, check some of the posts below.
- Python program to merge or concatenate two lists
- Find the Biggest and Smallest of 3 numbers using lists in Python
- Python Lists – Add, Append, Modify, Remove, Slice
- Python program to calculate the sum of elements in a list
- Python program to find the largest and smallest number in a list
- How to find Union of two lists in Python
- Python Program to separate even and odd numbers in a list
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