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 if 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. 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 number of times, such as on a huge input list or file.
Play around with generator functions. Start with basic iterators...