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.

Together with map, filter and reduce support powerful functional programmingtechniques. Some observers might also extend the functional programming toolset in<strong>Python</strong> to include lambda and apply, and list comprehensions, which are discussed inthe next section.List Comprehensions Revisited: MappingsBecause mapping operations over sequences and collecting results is such a commontask in <strong>Python</strong> coding, <strong>Python</strong> 2.0 sprouted a new feature—the list comprehensionexpression—that makes it even simpler than using the tools we just studied. We metlist comprehensions in Chapter 13, but because they’re related to functional programmingtools like the map and filter calls, we’ll resurrect the topic here for onelast look. Technically, this feature is not tied to functions—as we’ll see, list comprehensionscan be a more general tool than map and filter—but it is sometimes bestunderstood by analogy to function-based alternatives.List Comprehension BasicsLet’s work through an example that demonstrates the basics. As we saw inChapter 7, <strong>Python</strong>’s built-in ord function returns the ASCII integer code of a singlecharacter (the chr built-in is the converse—it returns the character for an ASCII integercode):>>> ord('s')115Now, suppose we wish to collect the ASCII codes of all characters in an entire string.Perhaps the most straightforward approach is to use a simple for loop, and appendthe results to a list:>>> res = []>>> for x in 'spam':... res.append(ord(x))...>>> res[115, 112, 97, 109]Now that we know about map, though, we can achieve similar results with a singlefunction call without having to manage list construction in the code:>>> res = map(ord, 'spam') # Apply function to sequence>>> res[115, 112, 97, 109]As of <strong>Python</strong> 2.0, however, we can get the same results from a list comprehensionexpression:>>> res = [ord(x) for x in 'spam'] # Apply expression to sequence>>> res[115, 112, 97, 109]List Comprehensions Revisited: Mappings | 355

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

Saved successfully!

Ooh no, something went wrong!