Elements of a list comprehension

Note that the source object over which we iterate in a list comprehension doesn't need to be a list itself. It can be any object with implements the iterable protocol, such as a tuple.

The expression part of the comprehension can be any Python expression. Here we find the number of decimal digits in each of the first 20 factorials using range() — which is an iterable object — to generate the source sequence:

>>> from math import factorial
>>> f = [len(str(factorial(x))) for x in range(20)]
>>> f
[1, 1, 1, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 18]

Note also that the type of the object produced by list comprehensions is nothing more or less than a regular list:

>>> type(f)
<class 'list'>

It's important to keep this fact in mind as we look at other kinds of comprehensions and consider how to perform iteration over infinite sequences.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset