Merge two lists based on index Python
Show Python list is one of the most commonly used datatypes. The list can hold different types of items. Each item can be accessed with its index. The index starts from 0, i.e. the index of the first element is 0, the index of the second element is 1 etc. We can access any element using its index. List is mutable. We can delete and change any element of a list. Square bracket ([]) is used for python lists. All items are placed inside a square bracket. For accessing an item, a square bracket is used with the list name. The index of the element is placed in the square bracket like my_list[0]. This will give us the element with index 0 in the list my_list. Our problem is to merge two lists and sort the items of the final merged list. We will use only integer numbers in both lists to make the sorting easier. Also, we will write the program to take the list values as inputs from the user. You can populate the lists with constant values at the starting of the program but a dynamic list will make the program more beautiful. Before start writing the code, let’s take a look at the algorithm : The algorithm to merge two lists and sort the merged list:
Python3 Program :first_list = [] second_list = [] count_first_list = int(input("Enter total numbers of the first list : ")) for i in range(1,count_first_list+1): no = int(input("Enter : ")) first_list.append(no) count_second_list = int(input("Enter total numbers of the second list : ")) for i in range(1,count_second_list+1): no = int(input("Enter : ")) second_list.append(no) print("First list : ",first_list) print("Second list : ",second_list) final_list = first_list + second_list final_list.sort() print("Final list : ",final_list) The source code is available here. Notes :
Sample outputs :Similar tutorials : |