@rkenmi - Intro to Python Lambda

Intro to Python Lambda


It's like anonymous functions for Python.

Intro to Python Lambda


Back to Top

Updated on February 6, 2017

Lambdas are simply anonymous functions for Python. We often don't want to write a whole new function with a name if the function itself only consists of one line of code. It is tedious, even though it might be less scary to see.

g = lambda x: x ** 2

The best way to read this is that for this iterable x, multiply each object in x to the power of 2 and return that value.

Alternatively it could be read as something like this:

g = def square(x):
    return x ** 2

Do beware, the above is just a visual heuristic and it is not valid Python syntax.

Speaking of heuristics, let's look at another lambda function that deals with A.I. heuristics.

Material: http://ai.berkeley.edu/search.html

h = lambda x: heuristic(x[0], problem)

heuristic is a function that takes in a node, and the search problem. But, never mind those two.

heuristic returns a number, which represents the distance from the node to the goal node. You can think of the search problem as a tree or graph that contains these nodes.

Anyhow, to demo-test heuristic, you can simply call:

print h( (problem.getStartState(),0,0) )

Another way to call:

print heuristic(problem.getStartState(), problem)

They both return the same heuristic number (Integer). The difference? When h is called, only the first parameter is used, namely the problem.getStartState(). The two other parameters in the tuple that h passes is ignored. heuristic doesn't take tuples, after all. They only take a node and the search problem.


Article Tags:
Pythonlambda function