Python:Lambda Function

From PrattWiki
Revision as of 01:12, 9 November 2019 by DukeEgr93 (talk | contribs) (Created page with "(page adapted from MATLAB:Anonymous Function) Python has a feature that lets you develop an analytical expression of one or more inputs and either assign that expressi...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

(page adapted from MATLAB:Anonymous Function) Python has a feature that lets you develop an analytical expression of one or more inputs and either assign that expression to a variable or pass it as an argument to a function. The lambda keyword lets you create an anonymous function of any number of variables by giving the lambda keyword, followed by a variable list, followed by the expression the function is meant to calculate. The expression can only be one line of code and can only return one item (to include returning a single list or tuple with multiple components).

This method is good for relatively simple functions that will not be used that often and that can be written in a single expression.

Syntax

The syntax for building an anonymous function is to put the lambda keyword, the variable list, and the expression all on one line. To give the anonymous function a name, simply put the function's name on the left side of an equal sign and the anonymous function on the right. For example, if you want \(c(a,b,\theta)\), to return \(\sqrt{a^2+b^2-2ab\cos(\theta)}\), you could create a function c by building an anonymous function and assigning it to the variable c as follows:

c = lambda a, b, theta: np.sqrt(a**2+b**2-2*a*b*np.cos(theta))

If you then ask what c is by typing it alone in the console and hitting return, Python will respond with:

In [1]: c
Out[1]: <function __main__.<lambda>(a, b, theta)>

indicating that the variable c is now actually a function handle that points to an anonymous function which takes three arguments. You can now use the function by putting numbers in for the arguments - for example:

side_three = c(2, 3, np.pi/6)
print(side_three)

will print

1.61483595284

You can also use that function to return entire arrays. For example, the commands:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

x,y = np.meshgrid(np.arange(0, 2.1, .1), np.arange(0, 2.1, 0.1))

fig = plt.figure(num=1)
fig.clf()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.plot_surface(x, y, c(x, y, np.pi/4))
ax.set(xlabel = 'Side 1', ylabel = 'Side 2', zlabel = 'Side 3')
ax.set(title = 'Triangle Third Side vs. Sides Surrounding a 45$^o$ Angle (mrg)')
fig.tight_layout()

will produce the graph:

InlineExamplePlotPython.png


Notes

  • Lambda functions can access variables in the console, and as such those variables must exist when a lambda function is called. If some part of a lambda function does not exist when the function is created, you will not see the error until the function is called.
In [1]: fun = lambda x: x + a

In [2]: fun(1)
Traceback (most recent call last):

  File "<ipython-input-34-a0060b8a4c19>", line 1, in <module>
    fun(1)

  File "<ipython-input-33-ed3dbd72778a>", line 1, in <lambda>
    fun = lambda x: x + a

NameError: name 'a' is not defined

In [3]: a = 10

In [4]: fun(1)
Out[4]: 11

In [5]: a = 30

In [6]: fun(1)
Out[6]: 31

Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References