Page 194 -
P. 194
list comprehensions
Now that you know about list comprehensions, you were to write
four of them to process the coach’s four lists of timing values. You
were to transform each of your lists into sorted, sanitized version
of themselves. You were to grab your pencil and in the space
provided, scribble the list comprehensions you plan to use.
The list comprehension
performs the
transformation, and the sorted([sanitize(t) for t in james])
new list is then ordered
by the “sorted()” BIF. sorted([sanitize(t) for t in julie])
Rinse and repeat
sorted([sanitize(t) for t in mikey]) for the other lists.
sorted([sanitize(t) for t in sarah])
Be careful about where you use
the sorted() BIF when defining
your list comprehensions.
You may have been tempted to use the
function chain sorted(sanitize(t))
within your list comprehension. Don’t be. Recall that the
transformation works on one list item at a time, not the
entire list. In this example, the sorted() BIF expects
to sort a list, not an individual data item.
The beauty of list comprehensions
The use of list comprehensions with the coach’s athlete data has resulted
in a lot less code for you to maintain. Additionally, as you get used to list
comprehension syntax and usage, you’ll find that their use is natural and
matches the way your brain thinks about your data and the transformations
that you might want to apply.
Let’s confirm that your new code is working as expected.
158 Chapter 5