How to Merge and Sort Two Lists in PythonIn this tutorial, we will write the program to sort and merge two lists using Python. We will solve this problem by using the two approaches – using another list or without using another space. Sort and Merge Two Lists using sort() MethodThe following program will take the two lists sort and merge them. Solution Approach
Let’s see the following code implementation. Example – Output: Enter number of elements for first list:5 Enter element: 2 Enter element: 3 Enter element: 1 Enter element: 5 Enter element: 4 Enter number of elements for second list: 5 Enter element: 14 Enter element: 13 Enter element: 11 Enter element: 12 Sorted list is: [1, 2, 3, 4, 5, 11, 12, 13, 14, 15] Explanation – We initialized two empty lists in the above code, list1, and list2, which hold the elements. The num variable stored the number of elements in list1 and list2. Then, the user must enter the list elements one by for loop and store them into the list. The ‘+’ operator merged both lists, and the sort() method sorted the list into the ascending order. Finally, we printed the sorted list. Sort and Merge Two Lists without Using Extra SpaceIn the previous example, we merged the two lists, creating a new list and then using the sort() method. In this section, we will sort and merge two lists without creating another list. Let’s understand the following example. Example – Output: Enter number of elements for first list: 4 Enter element: 10 Enter element: 12 Enter element: 17 Enter element: 9 Enter number of elements for first list: 4 Enter element: 5 Enter element: 18 Enter element: 20 Enter element: 89 Sorted list is: [5, 10, 12, 17, 18, 20, 89] Explanation – In the above code, we implemented the same functionalities to create two lists. The outer loop runs on the list1, and the inner loop runs on the second list, and it will run until the outer loop gets terminated. However, instead of creating the new sorted list, we appended the elements in the list2 after sorting. It checked the condition if the first element of list1 is greater than list2 and less than the second element of list2. Then, it inserted into list2 between the first and second elements of list2. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263238.html