12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Traceback (most recent call last):File "", line 1, in G.next( )StopIterationWe don’t typically see the next iterator machinery under the hood of a generatorexpression like this because for loops trigger it for us automatically:>>> for num in (x ** 2 for x in range(4)):... print '%s, %s' % (num, num / 2.0)...0, 0.01, 0.54, 2.09, 4.5In fact, every iteration context does this, including the sum, map, and sorted built-infunctions, and the other iteration contexts we learned about in Chapter 13, such asthe any, all, and list built-in functions.Notice that the parentheses are not required around a generator expression if theyare the sole item enclosed in other parentheses, like those of a function call. Extraparentheses are required, however, in the second call to sorted:>>> sum(x ** 2 for x in range(4))14>>> sorted(x ** 2 for x in range(4))[0, 1, 4, 9]>>> sorted((x ** 2 for x in range(4)), reverse=True)[9, 4, 1, 0]>>> import math>>> map(math.sqrt, (x ** 2 for x in range(4)))[0.0, 1.0, 2.0, 3.0]Generator expressions are primarily a memory space optimization—they do notrequire the entire result list to be constructed all at once, as the square-bracketed listcomprehension does. They may also run slightly slower in practice, so they are probablybest used only for very large result sets—which provides a natural segue to thenext section.Timing Iteration AlternativesWe’ve met a few iteration alternatives in this book. To summarize, let’s take a brieflook at a case study that pulls together some of the things we’ve learned about iterationand functions.366 | Chapter 17: Advanced Function Topics

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

Saved successfully!

Ooh no, something went wrong!