python tutorial - Python Functions lambda - learn python - python programming
Functions lambda
- Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called lambda.
- This is not exactly the same as lambda in functional programming languages such as Lisp, but it is a very powerful concept that's well integrated into Python and is often used in conjunction with typical functional concepts like filter(), map() and reduce().
- Like def, the lambda creates a function to be called later. But it returns the function instead of assigning it to a name.
- This is why lambdas are sometimes known as anonymous functions. In practice, they are used as a way to inline a function definition, or to defer execution of a code.
- The following code shows the difference between a normal function definition, func and a lambda function, lamb:
- As we can see, func() and lamb() do exactly the same and can be used in the same ways.
- Note that the lambda definition does not include a return statement -- it always contains an expression which is returned.
- Also note that we can put a lambda definition anywhere a function is expected, and we don't have to assign it to a variable at all.
- The lambda's general form is :
- Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs. However, there are a few differences that make lambda useful in specialized roles:
- lambda is an expression, not a statement.
- lambda's body is a single expression, not a block of statements.
- lambda is an expression, not a statement.
- Because of this, a lambda can appear in places a def is not allowed. For example, places like inside a list literal, or a function call's arguments.
- As an expression, lambda returns a value that can optionally be assigned a name. In contrast, the def statement always assigns the new function to the name in the header, instead of returning is as a result.
- lambda's body is a single expression, not a block of statements.
- The lambda's body is similar to what we'd put in a def body's return statement. We simply type the result as an expression instead of explicitly returning it.
- Because it is limited to an expression, a lambda is less general that a def. We can only squeeze design, to limit program nesting. lambda is designed for coding simple functions, and def handles larger tasks.
- We can achieve the same effect with lambda expression by explicitly assigning its result to a name through which we can call the function later:
- Here, f is assigned the function object the lambda expression creates. This is how def works, too. But in def, its assignment is an automatic must.
- Default work on lambda arguments:
- In the following example, the value for the name title would have been passes in as a default argument value:
Why lambda ?
- The lambdas can be used as a function shorthand that allows us to embed a function within the code.
- For instance, callback handlers are frequently coded as inline lambda expressions embedded directly in a registration call's arguments list.
- Instead of being define with a def elsewhere in a file and referenced by name, lambdas are also commonly used to code jump tables which are lists or dictionaries of actions to be performed on demand.
- In the example above, a list of three functions was built up by embedding lambda expressions inside a list.
- A def won't work inside a list literal like this because it is a statement, not an expression.
- If we really want to use def for the same result, we need temporary function names and definitions outside:
- We can use dictionaries doing the same thing:
- >>> key = 'quadratic' >>> {'square': (lambda x: x ** 2), 'cubic': (lambda x: x ** 3), 'quadratic': (lambda x: x ** 4)}[key](10) 10000 >>>
- Here, we made the temporary dictionary, each of the nested lambdas generates and leaves behind a function to be called later. We fetched one of those functions by indexing and the parentheses forced the fetched function to be called.
- Again, let's do the same thing without lambda.
- This works but our defs may be far away in our file. The code proximity that lambda provide is useful for functions that will only be used in a single context.
- Especially, if the three functions are not going to be used anywhere else, it makes sense to embed them within the dictionary as lambdas.
- Also, the def requires more names for these title functions that may cause name clash with other names in this file.
- If we know what we're doing, we can code most statements as expressions:
- If we need to perform loops within a lambda, we can also embed things like map calls and list comprehension expressions.
- Here is the description of map built-in function.
- map(function, iterable, ...)
- Return an iterator that applies function to every item of iterable, yielding the results.
- If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.
- With multiple iterables, the iterator stops when the shortest iterable is exhausted.
- So, in the above example, sys.stdout.write is an argument for function, and the x is an iterable item, list, in the example.
Nested lambda
- In the following example, the lambda appears inside a def and so can access the value that the name x has in the function's scope at the time that the enclosing function was called:
- Though not clear in this example, note that lambda also has access to the names in any enclosing lambda. Let's look at the following example:
- In the example, we nested lambda structure to make a function that makes a function when called. It's fairly convoluted and it should be avoided.
lambda and sorted()
- Here is a simple example of using lambda with built-in function sorted():
- The sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.
- In this example, we want to read a video file and sort the packet in the order of starting time stamp. Also, we want to count the number of chunks.
- After reading in the video using ffprobe, the data looks like this: