Skip to main content

Effective ways to sort Python iterables

The traditional way to sort iterables is by using loops, like for loop or while loop. As part of this article, I am not going to cover this traditional way, rather I will 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]
Python

To sort this list, we just need to call a function as shown below: 

numbers = sorted(numbers)
Python

To sort this list in reverse order, we need to pass an additional parameter:

numbers = sorted(numbers, reverse=True)
Python

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}
]
Python

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”])
Python

You can print studentDetails and check out the results.

Hope you like this cool tip. You can also watch the recoding of this entire flow on my YouTube channel named Shweta Lodha.


Comments