Text
stringlengths
1
9.41k
In Python, though, it’s really just a keyword that introduces the expression syntactically.
Obscure mathematical heritage aside, lambda is simpler to use than you may think. **|** ----- Apart from those distinctions, defs and lambdas do the same sort of work.
For instance, we’ve seen how to make a function with a def statement: ``` >>> def func(x, y, z): return x + y + z ... >>> func(2, 3, 4) 9 ``` But you can achieve the same effect with a lambda expression by explicitly assigning its result to a name through which you can later call the function: ``` >>> f = la...
lambda expressions introduce a local scope much like a nested def, which auto ``` matically sees names in enclosing functions, the module, and the built-in scope (via the LEGB rule): ``` >>> def knights(): ...
title = 'Sir' ``` `... action = (lambda x: title + ' ' + x)` _# Title in enclosing def_ `...
return action` _# Return a function_ ``` ... >>> act = knights() >>> act('robin') 'Sir robin' ``` In this example, prior to Release 2.2, the value for the name title would typically have been passed in as a default argument value instead; flip back to the scopes coverage in Chapter 17 if you’ve forgotten why. ...
They are entirely optional (you can always use defs instead), but they tend to be simpler coding constructs in scenarios where you just need to embed small bits of executable code. For instance, we’ll see later that callback handlers are frequently coded as inline ``` lambda expressions embedded directly in a registra...
For example: ``` L = [lambda x: x ** 2, # Inline function definition lambda x: x ** 3, lambda x: x ** 4] # A list of 3 callable functions for f in L: print(f(2)) # Prints 4, 8, 16 print(L[0](3)) # Prints 9 ``` The lambda expression is most useful as a shorthand fo...
The equivalent def coding would require temporary function names and function definitions outside the context of intended use: ``` def f1(x): return x ** 2 def f2(x): return x ** 3 # Define named functions def f3(x): return x ** 4 L = [f1, f2, f3] # Reference by name for f in L: print(f(2)...
Here’s another example to illustrate, at the interactive prompt: ``` >>> key = 'got' >>> {'already': (lambda: 2 + 2), ... 'got': (lambda: 2 * 4), ...
'one': (lambda: 2 ** 6)}[key]() 8 ``` Here, when Python makes the temporary dictionary, each of the nested lambdas generates and leaves behind a function to be called later.
Indexing by key fetches one of those functions, and parentheses force the fetched function to be called.
When coded this way, a dictionary becomes a more general multiway branching tool than what I could show you in Chapter 12’s coverage of if statements. To make this work without lambda, you’d need to instead code three def statements somewhere else in your file, outside the dictionary in which the functions are to be u...
The code proximity that lambdas provide is especially useful for functions that will only be used in a single context—if the three functions here are not useful anywhere else, it makes sense to embed their definitions within the dictionary as `lambdas.
Moreover, the` `def form requires you to make up names for these little` functions that may clash with other names in this file (perhaps unlikely, but always possible). ``` lambdas also come in handy in function-call argument lists as a way to inline temporary ``` function definitions not used anywhere else in your pr...
If you know what you’re doing, though, you can code most statements in Py ``` thon as expression-based equivalents. For example, if you want to print from the body of a `lambda function, simply say` ``` sys.stdout.write(str(x)+'\n'), instead of print(x) (recall from Chapter 11 that this ``` is what print really does)...
Similarly, to nest logic in a lambda, you can use the if/else ternary expression introduced in Chapter 12, or the equivalent but trickier and/or combination also described there.
As you learned earlier, the following statement: ``` if a: b else: c ``` can be emulated by either of these roughly equivalent expressions: ``` b if a else c ((a and b) or c) ``` Because expressions like these can be placed inside a lambda, they may be used to implement selection logic within a lambda...
Without due care, they can lead to unreadable (a.k.a. obfus_cated) Python code.
In general, simple is better than complex, explicit is better than_ implicit, and full statements are better than arcane expressions. That’s why lambda is limited to expressions.
If you have larger logic to code, use def; lambda is for small pieces of inline code.
On the other hand, you may find these techniques useful in moderation. ###### Nested lambdas and Scopes ``` lambdas are the main beneficiaries of nested function scope lookup (the E in the LEGB ``` scope rule we studied in Chapter 17).
In the following, for example, the lambda appears inside a def—the typical case—and so can access the value that the name x had in the enclosing function’s scope at the time that the enclosing function was called: ``` >>> def action(x): ``` `...
return (lambda y: x + y)` _# Make and return function, remember x_ ``` ... >>> act = action(99) >>> act <function <lambda> at 0x00A16A88> ``` `>>> act(2)` _# Call what action returned_ ``` 101 ``` What wasn’t illustrated in the prior discussion of nested function scopes is that a ``` lambda also has access ...
This case is somewhat ``` obscure, but imagine if we recoded the prior def with a lambda: ``` >>> action = (lambda x: (lambda y: x + y)) >>> act = action(99) >>> act(3) 102 ``` **|** ----- ``` >>> ((lambda x: (lambda y: x + y))(99))(4) 103 ``` Here, the nested lambda structure makes a function that ma...
This works, but it’s fairly convoluted code; in the interest of readability, nested lambdas are generally best avoided. ###### Why You Will Care: Callbacks ``` Another very common application of lambda is to define inline callback functions for Python’s tkinter GUI API (this module is named Tkinter in Python 2.6).
For example, the following creates a button that prints a message on the console when pressed, assuming tkinter is available on your computer (it is by default on Windows and other OSs): ``` import sys from tkinter import Button, mainloop # Tkinter in 2.6 x = Button( text ='Press me', comm...
The advantage of lambda over def here is that the code that handles a button press is right here, embedded in the button-creation call. In effect, the lambda _defers execution of the handler until the event occurs: the write_ call happens on button presses, not when the button is created. Because the nested function ...
For instance, updating all the counters in a list can be done easily with a for loop: **|** ----- ``` >>> counters = [1, 2, 3, 4] >>> >>> updated = [] >>> for x in counters: ``` `...
updated.append(x + 10)` _# Add 10 to each item_ ``` ... >>> updated [11, 12, 13, 14] ``` But because this is such a common operation, Python actually provides a built-in that does most of the work for you.
The map function applies a passed-in function to each item in an iterable object and returns a list containing all the function call results.
For example: `>>> def inc(x): return x + 10` _# Function to be run_ ``` ... ``` `>>> list(map(inc, counters))` _# Collect results_ ``` [11, 12, 13, 14] ``` We met map briefly in Chapters 13 and 14, as a way to apply a built-in function to items in an iterable.
Here, we make better use of it by passing in a user-defined function to be applied to each item in the list—map calls inc on each list item and collects all the return values into a new list.
Remember that `map is an iterable in Python 3.0, so a` ``` list call is used to force it to produce all its results for display here; this isn’t necessary ``` in 2.6. Because map expects a function to be passed in, it also happens to be one of the places where lambda commonly appears: `>>> list(map((lambda x: x + 3)...
Because such uses of map are equivalent to for loops, with a little extra code you can always code a general mapping utility yourself: ``` >>> def mymap(func, seq): ... res = [] ...
for x in seq: res.append(func(x)) ...
return res ``` Assuming the function inc is still as it was when it was shown previously, we can map it across a sequence with the built-in or our equivalent: `>>> list(map(inc, [1, 2, 3]))` _# Built-in is an iterator_ ``` [11, 12, 13] ``` `>>> mymap(inc, [1, 2, 3])` _# Ours builds a list (see generators)_ ``` [...
Moreover, map can be used in more advanced ways than **|** ----- shown here.
For instance, given multiple sequence arguments, it sends items taken from sequences in parallel as distinct arguments to the function: `>>> pow(3, 4)` _# 3**4_ ``` 81 ``` `>>> list(map(pow, [1, 2, 3], [2, 3, 4]))` _# 1**2, 2**3, 3**4_ ``` [1, 8, 81] ``` With multiple sequences, map expects an N-argument functio...
Here, the pow function takes two arguments on each call—one from each sequence passed to ``` map.
It’s not much extra work to simulate this multiple-sequence generality in code, ``` too, but we’ll postpone doing so until later in the next chapter, after we’ve met some additional iteration tools. The `map call is similar to the list comprehension expressions we studied in` Chapter 14 and will meet again in the nex...
Because of this limitation, it is a somewhat less general tool.
However, in some cases map may be faster to run than a list comprehension (e.g., when mapping a built-in function), and it may also require less coding. ###### Functional Programming Tools: filter and reduce The map function is the simplest representative of a class of Python built-ins used for _functional programmin...
Because they return iterables, range and ``` filter both require list calls to display all their results in 3.0.
For example, the fol ``` lowing filter call picks out items in a sequence that are greater than zero: `>>> list(range(−5, 5))` _# An iterator in 3.0_ ``` [−5, −4, −3, −2, −1, 0, 1, 2, 3, 4] ``` `>>> list(filter((lambda x: x > 0), range(−5, 5)))` _# An iterator in 3.0_ ``` [1, 2, 3, 4] ``` Items in the sequence o...
Like map, this function is roughly equivalent to a for loop, but it is built-in and fast: ``` >>> res = [] >>> for x in range(−5, 5): ... if x > 0: ...
res.append(x) ... >>> res [1, 2, 3, 4] reduce, which is a simple built-in function in 2.6 but lives in the functools module in ``` 3.0, is more complex.
It accepts an iterator to process, but it’s not an iterator itself—it **f** **|** ----- returns a single result.
Here are two reduce calls that compute the sum and product of the items in a list: `>>> from functools import reduce` _# Import in 3.0, not in 2.6_ ``` >>> reduce((lambda x, y: x + y), [1, 2, 3, 4]) 10 >>> reduce((lambda x, y: x * y), [1, 2, 3, 4]) 24 ``` At each step, reduce passes the current sum or product...
By default, the first item in the sequence` initializes the starting value.
To illustrate, here’s the for loop equivalent to the first of these calls, with the addition hardcoded inside the loop: ``` >>> L = [1,2,3,4] >>> res = L[0] >>> for x in L[1:]: ...
res = res + x ... >>> res 10 ``` Coding your own version of `reduce is actually fairly straightforward.
The following` function emulates most of the built-in’s behavior and helps demystify its operation in general: ``` >>> def myreduce(function, sequence): ... tally = sequence[0] ...
for next in sequence[1:]: ... tally = function(tally, next) ...
return tally ... >>> myreduce((lambda x, y: x + y), [1, 2, 3, 4, 5]) 15 >>> myreduce((lambda x, y: x * y), [1, 2, 3, 4, 5]) 120 ``` The built-in reduce also allows an optional third argument placed before the items in the sequence to serve as a default result when the sequence is empty, but we’ll leave this ...
Some observers might also extend the functional programming toolset in Python to include lambda, discussed earlier, as well as list comprehensions—a topic we will return to in the next chapter. ###### Chapter Summary This chapter took us on a tour of advanced function-related concepts: recursive functions; function a...
The next chapter continues the ``` advanced topics motif with a look at generators and a reprisal of iterators and list comprehensions—tools that are just as related to functional programming as to looping statements.
Before you move on, though, make sure you’ve mastered the concepts covered here by working through this chapter’s quiz. ###### Test Your Knowledge: Quiz 1.
How are lambda expressions and def statements related? 2. What’s the point of using lamba? 3. Compare and contrast map, filter, and reduce. 4. What are function annotations, and how are they used? 5.
What are recursive functions, and how are they used? 6. What are some general design guidelines for coding functions? ###### Test Your Knowledge: Answers 1.
Both lambda and def create function objects to be called later.
Because lambda is an expression, though, it returns a function object instead of assigning it to a name, and it can be used to nest a function definition in places where a def will not work syntactically.
A lambda only allows for a single implicit return value expression, though; because it does not support a block of statements, it is not ideal for larger functions. 2.
lambdas allow us to “inline” small units of executable code, defer its execution, and provide it with state in the form of default arguments and enclosing scope variables. Using a lambda is never required; you can always code a def instead and reference the function by name.
lambdas come in handy, though, to embed small pieces of deferred code that are unlikely to be used elsewhere in a program.
They commonly appear in callback-based program such as GUIs, and they have a natural affinity with function tools like map and filter that expect a processing function. **|** ----- 3.
These three built-in functions all apply another function to items in a sequence (iterable) object and collect results.
map passes each item to the function and collects all results, filter collects items for which the function returns a True value, and ``` reduce computes a single value by applying the function to an accumulator and ``` successive items.
Unlike the other two, reduce is available in the functools module in 3.0, not the built-in scope. 4.
Function annotations, available in 3.0 and later, are syntactic embellishments of a function’s arguments and result, which are collected into a dictionary assigned to the function’s __annotations__ attribute.
Python places no semantic meaning on these annotations, but simply packages them for potential use by other tools. 5.
Recursive functions call themselves either directly or indirectly in order to loop. They may be used to traverse arbitrarily shaped structures, but they can also be used for iteration in general (though the latter role is often more simply and efficiently coded with looping statements). 6.
Functions should generally be small, as self-contained as possible, have a single unified purpose, and communicate with other components through input arguments and return values.
They may use mutable arguments to communicate results too if changes are expected, and some types of programs imply other communication mechanisms. **|** ----- ###### CHAPTER 20 ### Iterations and Comprehensions, Part 2 This chapter continues the advanced function topics theme, with a reprisal of the comprehension...
Because list comprehensions are as much related to the prior chapter’s functional tools (e.g., map and filter) as they are to for loops, we’ll revisit them in this context here.
We’ll also take a second look at iterators in order to study generator functions and their generator expression relatives—user-defined ways to produce results on demand. Iteration in Python also encompasses user-defined classes, but we’ll defer that final part of this story until Part VI, when we study operator overlo...
As this is the last pass we’ll make over built-in iteration tools, though, we will summarize the various tools we’ve met thus far, and time the relative performance of some of them.
Finally, because this is the last chapter in the part of the book, we’ll close with the usual sets of “gotchas” and exercises to help you start coding the ideas you’ve read about. ###### List Comprehensions Revisited: Functional Tools In the prior chapter, we studied functional programming tools like `map and` `filte...
Because this is such a common task in Python coding, Python eventually sprouted a new expression—the _list_ _comprehension—that is even more flexible than the tools we just studied.
In short, list_ comprehensions apply an arbitrary expression to items in an iterable, rather than applying a function.
As such, they can be more general tools. We met list comprehensions in Chapter 14, in conjunction with looping statements. Because they’re also related to functional programming tools like the map and filter calls, though, we’ll resurrect the topic here for one last look.
Technically, this feature is not tied to functions—as we’ll see, list comprehensions can be a more general tool than map and filter—but it is sometimes best understood by analogy to function-based alternatives. ----- ###### List Comprehensions Versus map Let’s work through an example that demonstrates the basics.
As we saw in Chapter 7, Python’s built-in ord function returns the ASCII integer code of a single character (the chr built-in is the converse—it returns the character for an ASCII integer code): ``` >>> ord('s') 115 ``` Now, suppose we wish to collect the ASCII codes of all characters in an entire string. Perhaps ...
res.append(ord(x)) ... >>> res [115, 112, 97, 109] ``` Now that we know about `map, though, we can achieve similar results with a single` function call without having to manage list construction in the code: `>>> res = list(map(ord, 'spam'))` _# Apply function to sequence_ ``` >>> res [115, 112, 97, 109] `...
Syntactically, list comprehensions are enclosed in square brackets (to remind you that they construct lists).
In their simple form, within the brackets you code an expression that names a variable followed by what looks like a for loop header that names the same variable.
Python then collects the 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 the ``` map call.
List comprehensions become more convenient, though, when we wish to apply ``` 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 the interactive prompt print the result...
To do similar work with a map call, we would probably need to invent a little function to implement 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 a` ``` def statement elsewhere: >>> list(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 keys...
It’s also only marginally more complex (at least, once you understand the lambda). For more advanced kinds of expressions, though, list comprehensions will often require considerably less typing.
The next section shows why. ###### Adding Tests and Nested Loops: filter List comprehensions are even more general than shown so far.
For instance, as we learned in Chapter 14, you can code an if clause after the for to add selection logic. List comprehensions with if clauses can be thought of as analogous to the filter builtin discussed in the prior chapter—they skip sequence items for which the if clause is not true. To demonstrate, here are both ...
For comparison, the equivalent ``` for loop is shown here as well: >>> [x for x in range(5) if x % 2 == 0] [0, 2, 4] >>> list(filter((lambda x: x % 2 == 0), range(5))) [0, 2, 4] >>> res = [] >>> for x in range(5): ...
if x % 2 == 0: ...
res.append(x) ... >>> res [0, 2, 4] ``` All of these use the modulus (remainder of division) operator, %, to detect even numbers: if there is no remainder after dividing a number by 2, it must be even.
The filter call here is not much longer than the list comprehension either.
However, we can combine an if clause and an arbitrary expression in our list comprehension, to give it the effect of a filter _and a map, in a single expression:_ ``` >>> [x ** 2 for x in range(10) if x % 2 == 0] [0, 4, 16, 36, 64] ``` This time, we collect the squares of the even numbers from 0 through 9: the for...
The equivalent map call would require a lot more work **|** ----- on our part—we would have to combine filter selections with map iteration, making for a noticeably more complex expression: ``` >>> list( map((lambda x: x**2), filter((lambda x: x % 2 == 0), range(10))) ) [0, 4, 16, 36, 64] ``` In fact, list com...
You can code any number of nested ``` for loops in a list comprehension, and each may have an optional associated if test. ``` The general structure of list comprehensions looks like this: ``` [ expression for target1 in iterable1 [if condition1] for target2 in iterable2 [if condition2] ... for tar...