Read through section 10.7 of the book and do the examples.
We can write another reduce operation that subtracts all numbers from the first number. (I like to use more descriptive names for list variables that have specific properties. In this example, everything in the list must be a number.)
def subtract_all(numbers): """Returns the first number in numbers minus the sum of all other numbers.""" total = numbers[0] #only iterate through the numbers after the zeroeth for number in numbers[1:]: total -= number return total
In this example, total is still an accumulator, even though you're subtracting from it instead of adding. Also notice that we're using -=, which works just like +=. Try it out:
>>> subtract_all([5, 4, 3, 2, 1]) -5
The version of capitalize_all in the book is fruitful, but we could alternatively write this as a void method:
def capitalize_all(strings): """Capitalizes everything in a list of strings.""" #need the index in order to modify strings for i in range(len(strings)): strings[i] = strings[i].capitalize()
Since we're modifying the list, we don't want to return anything. This kind of function is called a modifier. If a function doesn't modify the input list, but instead returns a value, then it's known as a pure function. Map operations can be written either as a modifier or a pure function. They do very different things as far as your code is concerned!
Finally, the filter shown in the book is also created as a pure function. These can also be written as maps instead, though it requires some things we haven't yet learned.