4. Sorting & Reversing Methods in List
Python provides built-in methods to arrange the elements of a list and reverse their order. These are commonly used in data handling to sort data alphabetically, numerically, or reverse the current sequence.
sort()→ Sorts the list in ascending or descending order.reverse()→ Reverses the order of elements in the list.
Types of Sorting and Reversing Methods:
sort()— Sorts the list in increasing or decreasing order.reverse()— Reverses the elements of the list in-place.
1. Sorting Methods in Lists
Types of Sorting Methods:
sort()— Sorts the original list in-place.sort(reverse=True)— Sorts the list in descending order.sorted()— Returns a new sorted list (original remains unchanged).
1. sort()
The sort() method sorts the list in ascending order by default.
It changes (modifies) the original list.
Syntax:
list_name.sort()
Example:
marks = [70, 85, 60, 90]
marks.sort()
print(marks)
Output:
[60, 70, 85, 90]
Explanation:
sort()arranges the list in increasing order.- The original list is now changed to [60, 70, 85, 90].
2. sort(reverse=True)
We can pass reverse=True inside sort() to sort the list in
descending order.
Syntax:
list_name.sort(reverse=True)
Example:
marks = [70, 85, 60, 90]
marks.sort(reverse=True)
print(marks)
Output:
[90, 85, 70, 60]
Explanation:
reverse=Truetells Python to sort the list in descending order.- The original list is modified to [90, 85, 70, 60].
3. sorted()
The sorted() function returns a new sorted list, while keeping the
original list unchanged.
By default, it sorts the list in ascending order. To sort in
descending order,
pass the reverse=True argument.
Syntax:
new_list = sorted(list_name)
Example:
data = [40, 10, 30, 20]
sorted_data = sorted(data)
print("Sorted:", sorted_data)
print("Original:", data)
Output:
Sorted: [10, 20, 30, 40]
Original: [40, 10, 30, 20]
Explanation:
sorted()returns a new list in ascending order.- Original list remains unchanged.
2. reverse() Method
The reverse() method is used to reverse the elements of the list
in-place.
This means it directly modifies the original list and does not return a new list.
Syntax:
list_name.reverse()
Example:
students = ['Simran', 'Vanshu', 'Angel', 'Mukesh', 'Devanshi']
students.reverse()
print(students)
Output:
['Devanshi', 'Mukesh', 'Angel', 'Vanshu', 'Simran']
Explanation:
- The
reverse()method reversed the order of elements in the original list. - The original list was modified directly — no new list was created.
Summary:
sort()➔ Sorts the original list (ascending by default).sort(reverse=True)➔ Sorts the list in descending order.sorted()➔ Returns a new sorted list without changing the original.reverse()➔ Reverses the list elements in-place without sorting.