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.
Reading Items from a List
A list holds an ordered sequence of values:
scores = [90, 85, 77, 100]
You reach an item by its index, and indices start at 0, not 1:
scores[0] # 90 the first item scores[1] # 85 the second item scores[-1] # 100 the last item scores[-2] # 77 the second to last len(scores) # 4 how many items
Negative indices count backwards from the end. scores[-1] is much better than scores[len(scores) - 1], and it is what Python programmers actually write.
Asking for an index that does not exist raises IndexError. With 4 items the valid indices are 0, 1, 2 and 3, so scores[4] fails.
Your task:
Write first_and_last(values) that returns a tuple of the first item and the last item.
For [3, 9, 4, 7] it returns (3, 7). Assume the list has at least one item.
Example Tests
Picks the ends out of a four-item list
Input: {"values":[3,9,4,7]}
Expected: [3,7]
With two items, first and last are the two items
Input: {"values":[10,20]}
Expected: [10,20]
With one item, it is both the first and the last
Input: {"values":[42]}
Expected: [42,42]
def first_and_last(values):
"""
Return the first and last items of a list.
Args:
values: a non-empty list
Returns:
A tuple (first_item, last_item).
"""
# YOUR CODE HERE
passRun your code to see results
⌘↵ runs against the visible tests