Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.2 — Slicing, Sorting and Searching Lists
Python · Example 4 of 4

Rank orders: two passes with a stable sort

A shop wants the biggest orders first, and customers in alphabetical order when two orders are equal. itemgetter(1) is a ready-made recipe for "take item 1 of each tuple" (Topic 5.6 explains key=; Topic 6.1 explains the import).

A slice items[start:stop:step] takes a part of a list as a new list, and you can also assign to a slice to change many items at once. sorted() returns a new sorted list, sort() reorders in place, and key= chooses what to sort by.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given nums = [5, 3, 8, 1, 9, 2], print the first three items, the last two items, every second item, and the list in reverse. Do not change nums.

02

Sort names = ["mona", "Raj", "amit", "Zoya"] in a way that ignores capital letters and print the result. Print names afterwards to show it is unchanged.

03

Given scores = [72, 95, 88, 61], print the highest score, the lowest score and the average, and the three highest scores from best to worst.

Explain it without notes

01

How does a slice like items[1:4:2] work, and what does it return?

02

What is the difference between sorted(items) and items.sort()?

03

What does a stable sort mean, and why is it useful?

04

What does the key argument do, and how many times is it called?

Rank orders: two passes with a stable sort
Sign in to run this example in your browser.

Expected output

by customer: [('Asha', 450), ('Asha', 90), ('Meena', 450), ('Ravi', 1200)]
biggest first, ties by customer: [('Ravi', 1200), ('Asha', 450), ('Meena', 450), ('Asha', 90)]
original untouched: [('Meena', 450), ('Asha', 450), ('Ravi', 1200), ('Asha', 90)]