12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

List comprehensions collect the results of applying an arbitrary expression to asequence of values and return them in a new list. Syntactically, list comprehensionsare enclosed in square brackets (to remind you that they construct lists). In their simpleform, within the brackets you code an expression that names a variable followedby what looks like a for loop header that names the same variable. <strong>Python</strong> then collectsthe expression’s results for each iteration of the implied loop.The effect of the preceding example is similar to that of the manual for loop and themap call. List comprehensions become more convenient, though, when we wish toapply an arbitrary expression to a sequence:>>> [x ** 2 for x in range(10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]Here, we’ve collected the squares of the numbers 0 through 9 (we’re just letting theinteractive prompt print the resulting list; assign it to a variable if you need to retainit). To do similar work with a map call, we would probably invent a little function toimplement the square operation. Because we won’t need this function elsewhere,we’d typically (but not necessarily) code it inline, with a lambda, instead of using adef statement elsewhere:>>> map((lambda x: x ** 2), range(10))[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]This does the same job, and it’s only a few keystrokes longer than the equivalent listcomprehension. It’s also only marginally more complex (at least, once you understandthe lambda). For more advanced kinds of expressions, though, list comprehensions willoften require considerably less typing. The next section shows why.Adding Tests and Nested LoopsList comprehensions are even more general than shown so far. For instance, you cancode an if clause after the for, to add selection logic. List comprehensions with ifclauses can be thought of as analogous to the filter built-in discussed in the priorsection—they skip sequence items for which the if clause is not true. Here areexamples of both schemes picking up even numbers from 0 to 4; like the map listcomprehension alternative we just looked at, the filter version here invents a littlelambda function for the test expression. For comparison, the equivalent for loop isshown here as well:>>> [x for x in range(5) if x % 2 == 0][0, 2, 4]>>> filter((lambda x: x % 2 == 0), range(5))[0, 2, 4]>>> res = [ ]>>> for x in range(5):356 | Chapter 17: Advanced Function Topics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!