Sorting algorithms
Sorting means putting items in order. Bubble sort compares neighbours two by two and swaps them if they're in the wrong order; insertion sort inserts each item into its place in the already-sorted part, like arranging cards in your hand.
These simple sorts are slow on big lists. In real life, you use sorted() or .sort(), which rely on Timsort, a very fast algorithm. The key parameter chooses the sorting criterion and reverse=True reverses the order.
def bubble_sort(items):
items = items[:]
n = len(items)
for i in range(n):
for j in range(n - 1 - i):
if items[j] > items[j + 1]:
items[j], items[j + 1] = items[j + 1], items[j]
return items
print(bubble_sort([5, 2, 9, 1]))
print(sorted([5, 2, 9, 1], reverse=True))
students = [("Sara", 15), ("Ali", 18), ("Lea", 12)]
print(sorted(students, key=lambda s: s[1]))