sort, sorted, key and stability
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.
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.
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.
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
How does a slice like items[1:4:2] work, and what does it return?
What is the difference between sorted(items) and items.sort()?
What does a stable sort mean, and why is it useful?
What does the key argument do, and how many times is it called?
Expected output
sorted: ['Apple', 'banana', 'cherry', 'date', 'fig']
by length: ['fig', 'date', 'Apple', 'banana', 'cherry']
ignore case: ['Apple', 'banana', 'cherry', 'date', 'fig']
reverse: ['fig', 'date', 'cherry', 'banana', 'Apple']
original: ['banana', 'Apple', 'cherry', 'date', 'fig']
sort() returned: None
words now: ['Apple', 'banana', 'cherry', 'date', 'fig']
by length, ties keep order: ['fig', 'pear', 'kiwi', 'date', 'apple']
two levels: ['fig', 'date', 'kiwi', 'pear', 'apple']