List comprehensions

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 word in words]
[2, 5, 2, 4, 2, 4, 2, 3, 6]

Here the new list is formed by binding the name word to each value in words in turn and then evaluating len(word) to create the corresponding value in the new list. In other words, this constructs a new list containing the lengths of the string in words; it's hard to imagine a much more effective way of expressing that new list!

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

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