Sorting with a Key Function
Learn how to use the key= parameter of sorted() to control sort order — by length, absolute value, or case-insensitive alphabetical order.
You've used sorted() to sort numbers and strings. The key= parameter lets you control what each item is sorted by.
Sort a list of words by their length instead of alphabetically:
The key= parameter accepts any callable. Python applies it to each item before comparing:
What will be the output?
Use key=str.lower for a case-insensitive sort. This tells Python to call str.lower() on each item before comparing — it doesn't change the items themselves:
When you write key=str.lower, you pass the method as a reference (no parentheses). Python calls str.lower(item) on each item internally.
What will be the output?
Use key=abs to sort numbers by their absolute value:
What will be the output?
Combine key= with reverse=True to sort in descending order by your chosen key.
Sort words from longest to shortest:
What will be the output?
What will be the output?
What will be the output?