lambda in Python

In Python, lambda is a mechanism to create a small anonymous function. The function must take at least one parameter or more. The function body is restricted to a single expression. The lambda function can be passed anonymously to other functions that take a function as a parameter. Or it can be assigned a name and can be used just like a normal function, by calling by that name and passing it parameters.

# Syntax: lambda parameter(s): expression
lambda x: x     # Maps a parameter to itself
lambda x: x + 1 # Increments input parameter
lambda x: x * 2 # Doubles input

# Assign lambda a name
foo = lambda x: x * 2
foo( 10 )
# 20

For more info, see More Control Flow Tools.

Tried with: Python 3.2.2

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.