List comprehension syntax

The general form for a list comprehension is:

[ expr(item) for item in iterable ]

That is, for each item in the iterable on the right we evaluate the expression  expr(item) on the left (which is almost always, but not necessarily, in terms of the item). We use the result of that expression as the next element of the list we are constructing.

The comprehension above is the declarative equivalent of the following imperative code:

>>> lengths = []
>>> for word in words:
... lengths.append(len(word))
...
>>> lengths
[2, 5, 2, 4, 2, 4, 2, 3, 6]
..................Content has been hidden....................

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