
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort and Reverse a Given List in Python
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]
Advertisements