Python Practice › List Programs › Program 24
sort() vs sorted()
Write a Python program to sort a list with sort() and with sorted().
Input
[5, 2, 9, 1, 7]
Output
[1, 2, 5, 7, 9] [5, 2, 9, 1, 7] [9, 7, 5, 2, 1]
Approach
sorted()returns a new list;sort()sorts in place.
Solution
numbers = [5, 2, 9, 1, 7]print(sorted(numbers), numbers)numbers.sort(reverse=True)print(numbers)Output
[1, 2, 5, 7, 9] [5, 2, 9, 1, 7] [9, 7, 5, 2, 1]
Line by line
Line 2
The original order is unchanged by sorted().
Line 3
sort() changes the list; reverse=True gives descending order.
Learn the concept
New to this topic? Read the lesson, then come back.