Working With Iterables II

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:

Python
Output

The key= parameter accepts any callable. Python applies it to each item before comparing:

Python

What will be the output?

Python

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:

Python
Output

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?

Python

Use key=abs to sort numbers by their absolute value:

Python
Output

What will be the output?

Python

Combine key= with reverse=True to sort in descending order by your chosen key.

Sort words from longest to shortest:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python