Exercises
If you don't use comprehensions in your daily coding very often, the first thing you should do is search through some existing code and find some for
loops. See whether any of them can be trivially converted to a generator expression or a list, set, or dictionary comprehension.
Test the claim that list comprehensions are faster than for
loops. This can be done with the built-in timeit
module. Use the help documentation for the timeit.timeit
function to find out how to use it. Basically, write two functions that do the same thing, one using a list comprehension, and one using a for
loop to iterate over several thousand items. Pass each function into timeit.timeit
, and compare the results. If you're feeling adventurous, compare generators and generator expressions as well. Testing code using timeit
can become addictive, so bear in mind that code does not need to be hyperfast unless it's being executed...