Python program to sort and reverse a given list

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers in Python. We have to reverse and sort the lists using list operations but do not change the actual list. To reverse the list we have reverse() function for lists but if we use it, the list will be reversed in place. Similar for the sort() also. To maintain actual order we will use the reversed() function and sorted() function.

So, if the input is like l = [2,5,8,6,3,4,7,9], then the output will be [9, 7, 4, 3, 6, 8, 5, 2] [2, 3, 4, 5, 6, 7, 8, 9]

To solve this, we will follow these steps −

  • rev := list from the output iterator from reversed function output
  • display rev
  • srt := sort the list l using sorted() function
  • display srt

Example

Let us see the following implementation to get better understanding

def solve(l):
   rev = list(reversed(l))
   print (rev)

   srt = sorted(l)
   print(srt)

l = [2,5,8,6,3,4,7,9]
solve(l)

Input

[2,5,8,6,3,4,7,9]

Output

[9, 7, 4, 3, 6, 8, 5, 2] [2, 3, 4, 5, 6, 7, 8, 9]
raja
Updated on 11-Oct-2021 10:22:32

Advertisements