Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

lambda in Python

📅 2012-Apr-25 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ lambda, python ⬩ 📚 Archive

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


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧