10.6 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 statements. 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 the for statement. 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 statement 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 an immense...