Sorting
Basic non-mutating sorting is done with the built-in sorted() function:
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 5, 5, 6, 9]
If you have a more complex data structure that you need to sort, you can handle
it with the key parameter:
students = [
{"name": "John", "age": 25},
{"name": "Jane", "age": 22},
{"name": "Dave", "age": 23},
]
sorted_students = sorted(students, key=lambda student: student["age"])
print(sorted_students)
# Output: [{'name': 'Jane', 'age': 22}, {'name': 'Dave', 'age': 23}, {'name': 'John', 'age': 25}]
You can manipulate the sorting order with the reverse parameter:
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # Output: [9, 6, 5, 5, 2, 1]