Mike Driscoll
Mike Driscoll

@driscollis

5 Tweets 5 reads Jan 28, 2023
#Python includes several different ways to sort things. One handy way to sort is to use the built-in `sorted()` function!
Let's learn about that today!
#python_builtins_by_driscollis
πŸ§΅πŸπŸ‘‡
The `sorted()` function takes in an iterable and a couple of optional arguments.
In this example, you pass in a Python list and sort it from smallest to largest.
Then you set the optional `reverse` argument to True and sort from largest to smallest! 🐍πŸ”₯
The `sorted()` function also takes an optional `key` parameter. This parameter is a function that is used to modify the sorting behavior.
In this example, you use `str.lower()` to sort the words of a sentence. It will compare all the words in lowercase while sorting.
This last example shows how to sort a list of tuples. You can use the optional `key` parameter to sort by different items within the tuple using a `lambda`
In this case, you sort by student age!
Note: This example comes from the Python docs: docs.python.org
Thanks for learning about how to use Python's `sorted()` function with me.
Follow me for more great tips on #Python!

Loading suggestions...