Think you know your way around a Python list? Let’s put those skills to the test!
List slicing is one of the most powerful (and sometimes confusing) fundamental concepts in Python. Whether you’re cleaning data or building an app, getting your indices right is key.
The challenge: given the list
fruits = ["apple", "banana", "cherry", "date", "fig"]
what does fruits[1:4] return?
['apple', 'banana', 'cherry']['banana', 'cherry', 'date']['banana', 'cherry', 'date', 'fig']['cherry', 'date']The answer is B. ['banana', 'cherry', 'date'].
Index 1 is "banana" (included), and the slice stops just before index 4 (which is "fig"), so "date" is the last element returned.
fruits = ["apple", "banana", "cherry", "date", "fig"]
fruits[1:4] # ['banana', 'cherry', 'date']
The Stop Rule. Python slicing includes the start index but excludes the stop index. Think of it as
[inclusive : exclusive].
Now let’s turn that quiz into actual practice. No multiple choice this time: write the code, hit submit, and let Dodona check it.
Write a function extract_slice(items, start, stop) that takes a list items together with two integers start and stop, and returns the slice of items from start (inclusive) to stop (exclusive). In other words, your function should behave exactly like the built-in slicing expression items[start:stop].
>>> extract_slice(["apple", "banana", "cherry", "date", "fig"], 1, 4)
['banana', 'cherry', 'date']
>>> extract_slice([10, 20, 30, 40, 50], 0, 3)
[10, 20, 30]
>>> extract_slice([100, 200, 300, 400, 500], -3, -1)
[300, 400]
>>> extract_slice([1, 2, 3], 2, 2)
[]
Tip. Python’s slicing handles all the awkward cases for you: negative indices count from the end of the list, a
stopvalue past the end of the list is silently clamped, andstart == stopproduces an empty list. A single, correct one-liner covers every case the judge will throw at you.