Slices in action
Change the numbers in the brackets and predict each result first.
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
nums[1:4] [20, 30, 40]
nums[:3] [10, 20, 30]
nums[3:] [40, 50, 60]
nums[-2:] [50, 60]
nums[::2] [10, 30, 50]
nums[::-1] [60, 50, 40, 30, 20, 10]
nums[2:100] [30, 40, 50, 60]
copy: [999, 20, 30, 40, 50, 60]
original: [10, 20, 30, 40, 50, 60]
after slice assignment: [10, 21, 22, 23, 40, 50, 60]
after del: [22, 23, 40, 50, 60]