Sorting Lists
list.sort() changes the list in place and returns None. sorted() returns a new sorted list and works on any iterable. Add reverse=True for descending order and key= to choose what to sort by.
Example
nums = [5, 2, 9, 1]
print(sorted(nums))
print(sorted(nums, reverse=True))
nums.sort()
print(nums)
words = ["pear", "fig", "banana"]
print(sorted(words, key=len))
people = [("Ada", 30), ("Tunde", 22)]
print(sorted(people, key=lambda p: p[1]))Result
[1, 2, 5, 9]
[9, 5, 2, 1]
[1, 2, 5, 9]
['fig', 'pear', 'banana']
[('Tunde', 22), ('Ada', 30)]Exercise
Sort without changing the original.
new = (old)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.