Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

20. Iterations and Comprehensions, Part ... > Iterators Revisited: Generators - Pg. 494

The first of these makes use of tuple assignment to unpack row tuples in the list, and the second uses indexing. In Python 2.6 (but not in 3.0--see the note on 2.6 argument unpacking in Chapter 18), map can use tuple unpacking on its argument, too: # 2.6 only >>> list(map((lambda (name, age, job): age), listoftuple)) [35, 40] See other books and resources for more on Python's database API. Beside the distinction between running functions versus expressions, the biggest dif- ference between map and list comprehensions in Python 3.0 is that map is an iterator, generating results on demand; to achieve the same memory economy, list comprehen- sions must be coded as generator expressions (one of the topics of this chapter). Iterators Revisited: Generators Python today supports procrastination much more than it did in the past--it provides tools that produce results only when needed, instead of all at once. In particular, two language constructs delay result creation whenever possible: · Generator functions are coded as normal def statements but use yield statements to return results one at a time, suspending and resuming their state between each. · Generator expressions are similar to the list comprehensions of the prior section, but they return an object that produces results on demand instead of building a