Today I Learned

A Hashrocket project

Lambdas can only be one line

Unfortunately, lambdas in Python are limited. They can be only one expression.

This works:

print_twice = lambda word: print(word * 2)
# prints: "wordword"

But you can’t assign the intermediate value to a variable.

print_twice = lambda word: result = word * 2; print result;
# Syntax error

White space is significant is this language, so there are no () {} or keywords that would help you out here.

lambdas are the only way to define anonymous functions in python, but you can still define a named function in any context.

def build_fn(a):
    def adder(b):
        return b + a
    return adder

add3 = build_fn(3)
add3(4)
# 7