Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Slicing a List
A slice takes a section of a list and gives you back a new list:
letters = ["a", "b", "c", "d", "e"] letters[1:4] # ["b", "c", "d"] letters[:3] # ["a", "b", "c"] from the start letters[2:] # ["c", "d", "e"] to the end letters[-2:] # ["d", "e"] the last two
The rule that catches everyone: the start is included, the stop is not. [1:4] gives you indices 1, 2 and 3. That sounds annoying until you notice it means letters[:n] and letters[n:] split the list perfectly with no overlap and nothing missed.
A slice never raises IndexError. Asking for more than exists just gives you what there is:
letters[0:100] # the whole list, no error
Your task:
Write middle_three(values) that returns the items at index 1, 2 and 3 as a new list.
For [10, 20, 30, 40, 50] it returns [20, 30, 40].
Example Tests
Takes the three middle items of a five-item list
Input: {"values":[10,20,30,40,50]}
Expected: [20,30,40]
The stop index is excluded, so index 4 is not included
Input: {"values":[0,1,2,3,4]}
Expected: [1,2,3]
A short list returns whatever exists, without an error
Input: {"values":[1,2]}
Expected: [2]
def middle_three(values):
"""
Return the items at indices 1, 2 and 3.
Args:
values: a list
Returns:
A new list with those items.
"""
# YOUR CODE HERE
passRun your code to see results
⌘↵ runs against the visible tests