04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

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

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

134 CHAPTER 6 ■ ABSTRACTION<br />

LAMBDA EXPRESSIONS<br />

In the material that follows, I sometimes use something called lambda expressions. These are small, unnamed<br />

functions that can only contain an expression, and that return its value. A lambda expression is written like this:<br />

lambda x, y, z: x + y + z<br />

The first word, lambda, is a reserved word (keyword). 1 It is followed by the parameters, a colon (:), and<br />

finally the body (an expression).<br />

Although lambdas can be useful at times, you are usually better off writing a full-fledged function, especially<br />

because the function name will then say something about what your function does.<br />

map<br />

The map function “maps” one sequence into another (of the same length) by applying a function<br />

to each of the elements. For example, you may have a list of numbers, and you want to create<br />

another list in which all the numbers are doubled:<br />

>>> numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]<br />

>>> map(lambda n: 2*n, numbers)<br />

[144, 202, 216, 216, 222, 88, 64, 238, 222, 228, 216, 200, 66]<br />

You don’t have to use lambda expressions—it works just fine with named functions as well:<br />

>>> map(chr, numbers)<br />

['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!']<br />

The built-in function chr takes a number as its only parameter and returns the character<br />

corresponding to that number (the so-called ordinal number, which is really its ASCII code).<br />

The reverse of chr is ord:<br />

>>> map(ord, 'Hello, world!')<br />

[72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]<br />

Because strings are just sequences of characters, you can use map directly. Note that the<br />

result is a list, not another string. See the following section for a note about map, filter, and list<br />

comprehensions.<br />

filter<br />

The filter function returns a new list in which the elements that you don’t want have been<br />

filtered out. Or, to put it another way, it returns exactly those you do want. You supply filter<br />

with a function that returns a Boolean (truth) value for a given sequence element. If the function<br />

returns true, the element is part of the returned sequence; if it returns false, the element is not<br />

included in the returned sequence. (The original sequence is not modified.) For example, you<br />

might want to retain only the even numbers from the list numbers:<br />

1. The name “lambda” comes from the Greek letter λ, which is used in mathematics to indicate an<br />

anonymous function.

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

Saved successfully!

Ooh no, something went wrong!