June 2017
Beginner
352 pages
8h 39m
English
As hinted at above, a list comprehension is a short-hand way of creating a list. It's an expression using a succinct syntax that describes how list elements are defined. Comprehensions are much easier to demonstrate than they are to explain, so let's bring up a Python REPL. First we'll create a list of words by splitting a string:
>>> words = "If there is hope it lies in the proles".split()>>> words['If', 'there', 'is', 'hope', 'it', 'lies', 'in', 'the', 'proles']
Now comes the list comprehension. The comprehension is enclosed in square brackets just like a literal list, but instead of literal elements it contains a fragment of declarative code which describes how to construct the elements of the list:
>>> [len(word) for ...
Read now
Unlock full access