Sorting helps organize items in order, like arranging books by title. Reversing flips the order, like turning a stack upside down.
0
0
Sorting and reversing lists in Python
Introduction
When you want to list names alphabetically.
When you need to show numbers from smallest to largest.
When you want to see the newest messages first by reversing the list.
When you want to quickly find the highest or lowest value after sorting.
When you want to undo the order of a list for a different view.
Syntax
Python
my_list = [3, 1, 4, 2] # Sort the list in ascending order my_list.sort() # Sort the list in descending order my_list.sort(reverse=True) # Reverse the list order (no sorting) my_list.reverse()
sort() changes the list itself.
reverse() flips the list order without sorting.
Examples
Sorting an empty list keeps it empty.
Python
numbers = []
numbers.sort()
print(numbers)Sorting a list with one item keeps it the same.
Python
letters = ['a'] letters.sort() print(letters)
Sorts the list alphabetically.
Python
fruits = ['banana', 'apple', 'cherry'] fruits.sort() print(fruits)
Sorts the list in reverse alphabetical order.
Python
fruits = ['banana', 'apple', 'cherry'] fruits.sort(reverse=True) print(fruits)
Reverses the list order without sorting.
Python
numbers = [1, 2, 3] numbers.reverse() print(numbers)
Sample Program
This program shows how to sort a list in ascending and descending order, then reverse it. It prints the list at each step so you can see the changes.
Python
def print_list_state(label, items): print(f"{label}: {items}") numbers = [5, 2, 9, 1, 5, 6] print_list_state("Original list", numbers) # Sort ascending numbers.sort() print_list_state("Sorted ascending", numbers) # Sort descending numbers.sort(reverse=True) print_list_state("Sorted descending", numbers) # Reverse the list numbers.reverse() print_list_state("Reversed list", numbers)
OutputSuccess
Important Notes
Sorting with sort() changes the original list and runs in O(n log n) time.
Reversing with reverse() runs in O(n) time and just flips the list order.
Common mistake: Using sorted() returns a new sorted list but does not change the original list.
Use sort() when you want to change the list order permanently. Use reverse() when you want to flip the current order.
Summary
Use list.sort() to arrange items in order.
Use list.sort(reverse=True) to sort in reverse order.
Use list.reverse() to flip the list order without sorting.