Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to sort and reverse a given list
When working with lists in Python, you often need to sort or reverse them without modifying the original list. Python provides sorted() and reversed() functions that return new objects, unlike sort() and reverse() which modify the list in-place.
Problem Statement
Given a list of numbers, create a reversed version and a sorted version without changing the original list.
Example Input and Output
If the input is l = [2, 5, 8, 6, 3, 4, 7, 9], the output should be ?
Reversed: [9, 7, 4, 3, 6, 8, 5, 2] Sorted: [2, 3, 4, 5, 6, 7, 8, 9]
Solution Approach
To solve this problem, we will follow these steps ?
-
rev:= create a list fromreversed()function output - Display the reversed list
-
srt:= sort the list usingsorted()function - Display the sorted list
Implementation
def solve(l):
rev = list(reversed(l))
print("Reversed:", rev)
srt = sorted(l)
print("Sorted:", srt)
# Test the function
l = [2, 5, 8, 6, 3, 4, 7, 9]
solve(l)
# Verify original list is unchanged
print("Original:", l)
Reversed: [9, 7, 4, 3, 6, 8, 5, 2] Sorted: [2, 3, 4, 5, 6, 7, 8, 9] Original: [2, 5, 8, 6, 3, 4, 7, 9]
How It Works
The reversed() function returns an iterator that accesses the list in reverse order. Converting it to a list with list() creates a new reversed list. The sorted() function returns a new sorted list without modifying the original.
Key Points
-
reversed()returns an iterator, so wrap it withlist() -
sorted()directly returns a new sorted list - Original list remains unchanged throughout the process
- Both functions work with any iterable, not just lists
Conclusion
Use reversed() and sorted() to create new reversed and sorted versions of a list without modifying the original. This approach preserves data integrity while providing the required transformations.
