lambdaExpert Examples

Creates a small anonymous (unnamed) function in a single expression

Lambda vs def internals

Comparing lambda and def at the bytecode level.

python
import dis

# Lambda
fn1 = lambda x, y: x + y

# Equivalent def
def fn2(x, y):
    return x + y

print("Lambda bytecode:")
dis.dis(fn1)
print("\ndef bytecode:")
dis.dis(fn2)

# They compile to identical bytecode
print(f"\nLambda name: {fn1.__name__}")
print(f"def name: {fn2.__name__}")
print(f"Same code: {fn1.__code__.co_code == fn2.__code__.co_code}")

lambda and def compile to the same bytecode. The only differences are: lambda's __name__ is '<lambda>', and lambda can only contain a single expression.

Want to try these examples interactively?

Open Expert Playground