June 2017
Beginner
352 pages
8h 39m
English
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 ...
Read now
Unlock full access