sort() vs sorted()
Write a Python program to sort a list with sort() and with sorted().
[5, 2, 9, 1, 7]
[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)[1, 2, 5, 7, 9] [5, 2, 9, 1, 7] [9, 7, 5, 2, 1]
Line by line
The original order is unchanged by sorted().
sort() changes the list; reverse=True gives descending order.
Learn the concept
New to this topic? Read the lesson, then come back.