Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
The key argument
4. Stable algorithms
Lambdas
The itemgetter() function
Summary

Instruction

Very well done! One thing we haven't discussed is what happens when the order of two list items is identical. Let's take a look at the previous example again:

products = [
  'SuperPower3000', 'maxVoltage 2', 
  'ELECTROKING', 'aMpLiFiEr 52S',
  'AlternatingCurrent', 'el3ctric 2.0'
]

sorted(products, key=len)

In the code above, we sort the products by their length, but 'maxVoltage 2' and 'el3ctric 2.0' both have 12 characters. Which of them should be placed first in the list and why? Let's run the code and see the result.

Exercise

Run the template code, and note the order of 'maxVoltage 2' and 'el3ctric 2.0', both of which contain 12 characters.

As you can see, 'maxVoltage 2' appears before 'el3ctric 2.0'. In Python, sort() and sorted() are stable algorithms. This means that when multiple items have the same sort key, the items' original order will be preserved. 'maxVoltage 2' appeared before 'el3ctric 2.0' in the original list, and this order was preserved after sorting.