# Sorting

In this lesson, you’ll learn how to sort iterables in Python. You can either use the `sorted()` built-in function, or `.sort()` method. You can pass in the optional `key` parameter to specify how to sort the iterable, and you can reverse with the `reverse` parameter:

>>>
``````>>> animals = [{'type': 'cat', 'name': 'Stephanie', 'age': 8}, {'type': 'dog', 'name': 'Devon', 'age': 3}, {'type': 'rhino', 'name': 'Moe', 'age': 5}]
>>> sorted(animals, key=lambda animal: animal['age], reverse=True)
[{'type': 'cat', 'name': 'Stephanie', 'age': 8}, {'type': 'rhino', 'name': 'Moe', 'age': 5}, {'type': 'dog', 'name': 'Devon', 'age': 3}]
``````

If you want to learn more, check out Sorting Data With Python.

Piotr

Isn’t it somewhat wrong to suggest to use sorting to get the oldest animal in your example?

I don’t reckon the interviewer would be impressed to see a O(n log n) solution instead of simple iteration over a list resulting in a O(n).

James Uejio RP Team

@Piotr that is a great point and yes it would be better to iterate over it and get the max value that way. I do that in Part 4.

James Uejio RP Team

If you want to learn more, here is a Real Python walkthrough video on sorting: Sorting Data With Python

elmorem

I appreciate this video and the clever little tip about the key parameter with dictionaries. Plus, no one would reasonably conclude that a little python magic like this means the underlying algorithm is somehow faster. also, as far as i’m following this, iterating over the list and then getting the max to produce the sort isn’t going to happen in O(n) time.

shangcode

^_^ A single quotation is missing in Description tab. Animal[‘age’]

to join the conversation.

Lesson Completed!
Lesson Bookmarked
Request Failed :(