WeCodeAcademy

Sorting in Practice

You will rarely write a sort yourself. Python's sorted(items) returns a new sorted list and items.sort() sorts in place, both in O(n log n). Add reverse=True for descending order and key= to say what to sort by.

key takes a function that returns the value to compare. Sorting is stable: items that compare equal keep their original order, so you can sort by one thing and then another.

Examplepython
Open in editor »
Quick check

What does `key=len` do in `sorted(words, key=len)`?

Your turn: write the code

Sort the products by price, cheapest first, and print just the names as a list.

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.