Here we can see that the list is now sorted by the first item in the sub-list in ascending order. So, taking a new list, let's test it out by sorting by the first item in each sub-list: Let me illustrate, for your superb eyes only, the key keyword argument! The function gets an "invisible" argument passed to it that represents an item in the list, and returns a value that you would like to be the item's "key" for sorting. What key does is it provides a way to specify a function that returns what you would like your items sorted by. This is a little more complicated, but still pretty easy, so don't fret! Both the sorted function and the sort function take in a keyword argument called key. Okay, now let's see how to sort something a little more complicated. Keeping that in mind, here's how to do it: They must always use the sorted function to return a sorted list. Since tuples are arrays that you cannot modify, they don't have an in-place sort function that can be called directly on them. What about tuples, you say? I'm getting to that. We'll use this information later to make our own objects sortable. The return value is 0 for equal to, 1 for greater than, and -1 for less than the compared value. It calls the function _cmp_ on each object when comparing values, and decides which one to put in front of the other based on the value returned from _cmp_. What is Python doing behind the scenes? It's calling a version of mergesort on the list. Both functions take in the same arguments and can be treated as "the same" for our purposes here, except for the reason above. All we do is call sort on the list, for in-place sorting, or the built in function sorted for not modifying the original list and returning a new sorted list. Okay, so if you only want to sort a list of numbers, Python has a built in function that does all the hard work for you.Īnd we want to sort them in ascending order. Sorting a list or tuple is easy in Python! Since a tuple is basically like an array that is not modifiable, we'll treat it almost the same as a list. Last Updated: Wednesday 29 th December 2021
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |