Hello everyone, welcome back to programminginpython.com. Here in this post am going to tell you how to concatenate / merge lists.
You can watch this video on Youtube here
Add, merge or concatenate lists – Code Visualization
Task:
To merge / add / concatenate lists.
Approach:
- Read input number asking for length of the list using
input()orraw_input(). - Initialise 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 / merge / concatenate two lists
lst + lst2 - Print the resultant list of the above operation.
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
__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:
