The traditional way to sort iterables is by using loops, like for loop or while loop. As part of this article, I’m not going to cover this traditional way, rather I’ll be focusing on a better way to implement sorting.
And that better way is by using sorted function.
Let’s take a look at below list holding some numbers:
numbers = [2,3,6,4,9,1]
To sort this list, we just need to call a function as shown below:
numbers = sorted(numbers)
To sort this list in reverse order, we need to pass an additional parameter:
numbers = sorted(numbers, reverse=True)
Apart from this simple case, we can also handle some complex scenarios wherein we have a list containing key-value pairs as shown:
studentDetails = [
{“Name”: “Nick”, “Marks”: 23},
{“Name”: “Roy”, “Marks”: 2},
{“Name”: “Honey”, “Marks”: 45}
]
Now, say you want to sort studentDetails based on Marks. So, the only code you need to write to perform sorting is:
studentDetails = sorted(studentDetails, key=lambda k:k[“Marks”])
You can print studentDetails and check out the results.
Hope you like this cool tip. If interested, you can watch out the recording of this video here.