From the course: Python Standard Library Essential Training

Unlock the full course today

Join today to access over 22,700 courses taught by industry experts or purchase this course individually.

Sorting stability

Sorting stability - Python Tutorial

From the course: Python Standard Library Essential Training

Start my 1-month free trial

Sorting stability

- Pythons built-in sorting algorithms guarantee that sorts are stable. And what that means, is that, when multiple objects are being sorted and they have the same key value, the original order in the data list is preserved. So to demonstrate this, let's take another look at our previous sorting example. So let's open up, sortstable_start and here in the code I've added another Product object named "Doohickey" with the same price but with a different weight. This one has the weight of 10 whereas the original has a weight of eight. So when I run the code that I already have here, you can see in the output that the "Doohickey" object with a price of 40 and a weight of 10, came before the one with a price of 40 and a weight of eight. And that's because that's the order they were encountered in the list. So because of this rule, it's possible to build complex sorts using a series of steps. So for example, suppose we wanted to sort our list of objects by descending price but then by…

Contents