Page 190 -
P. 190
duplicated code
Hang on a sec! Something doesn’t feel quite
right...look at all that duplicated code, as well as
all those duplicated lists. This duplication is bad,
right? Is this really the best you can do?
That’s right. Duplicated code is a problem.
As things stand, your code creates four lists to hold the data as read
from the data files. Then your code creates another four lists to hold
the sanitized data. And, of course, you’re iterating all over the
place…
There has to be a better way to write code like this.
Transforming lists is such a common requirement that Python
provides a tool to make the transformation as painless as
possible. This tool goes by the rather unwieldly name of list
comprehension. And list comprehensions are designed to reduce
the amount of code you need to write when transforming one list
into another.
154 Chapter 5