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.
Lists Are Passed by Reference
Here is a bug that costs people hours the first time they hit it.
def add_bonus(scores):
scores.append(100)
return scores
original = [70, 80]
result = add_bonus(original)
result # [70, 80, 100]
original # [70, 80, 100] <- the caller's list changed too!When you pass a list to a function, the function gets the same list, not a copy. Anything it changes, the caller sees.
For numbers and strings this cannot happen, because they cannot be changed at all. For lists and dictionaries it happens by default.
To leave the caller's data alone, work on a copy:
copy = scores[:] # a slice of everything is a copy copy = list(scores) # so is this copy = scores.copy() # and this
Your task:
Write with_bonus(scores, bonus) that returns a new list with bonus added to the end. The list you were given must be unchanged afterwards.
The tests check both the returned value and that the input survived.
Example Tests
The bonus is added to the end of the returned list
Input: {"bonus":100,"scores":[70,80]}
Expected: [70,80,100]
Adding to an empty list gives a one-item list
Input: {"bonus":5,"scores":[]}
Expected: [5]
The original list is left untouched (this is what catches append-in-place)
Input: {"bonus":3,"scores":[1,2]}
Expected: [1,2]
def with_bonus(scores, bonus):
"""
Return a new list with one extra value on the end.
Args:
scores: a list of numbers. Must not be modified.
bonus: the value to add
Returns:
A new list: the original values followed by bonus.
"""
# YOUR CODE HERE
pass
def _check_unchanged(scores, bonus):
"""Calls with_bonus and reports the caller's list afterwards."""
original = list(scores)
with_bonus(scores, bonus)
return list(scores)Run your code to see results
⌘↵ runs against the visible tests