Python: Lambda

By Xah Lee. Date: .

lambda is used to define a nameless function.

💡 TIP: python lambda body must be in a single line. Usually for simple functions. If you need more than one line, use def Python: Function.

# lambda with one arg
# a function that adds 1
print((lambda x: x + 1)(3) == 4)
# lambda with two args
# a function that adds two numbers
print((lambda x, y: x + y)(3, 4) == 7)
# give lambda a name
ff = lambda x: x + 1

print(ff(3) == 4)
# add 2 numbers
ff = lambda x, y: x + y

print(ff(3, 4) == 7)

lambda is often used with map or filter.

xx = [1, 2, 3, 4, 5]

# keep just even numbers
yy = filter(lambda x: x % 2 == 0, xx)

print(list(yy) == [2, 4])

Python Function and Class