Lambda Inline, Anonymous Functions

suggest change

The lambda keyword creates an inline function that contains a single expression. The value of this expression is what the function returns when invoked.

Consider the function:

def greeting():
    return "Hello"

which, when called as:

print(greeting())

prints:

Hello

This can be written as a lambda function as follows:

greet_me = lambda: "Hello"
See note at the bottom of this section regarding the assignment of lambdas to variables. Generally, don’t do it.

This creates an inline function with the name greet_me that returns Hello. Note that you don’t write return when creating a function with lambda. The value after : is automatically returned.

Once assigned to a variable, it can be used just like a regular function:

print(greet_me())

prints:

Hello

lambdas can take arguments, too:

strip_and_upper_case = lambda s: s.strip().upper()

strip_and_upper_case("  Hello   ")

returns the string:

HELLO

They can also take arbitrary number of arguments / keyword arguments, like normal functions.

greeting = lambda x, *args, **kwargs: print(x, args, kwargs)
greeting('hello', 'world', world='world')

prints:

hello ('world',) {'world': 'world'}

lambdas are commonly used for short functions that are convenient to define at the point where they are called (typically with sorted, filter and map).

For example, this line sorts a list of strings ignoring their case and ignoring whitespace at the beginning and at the end:

sorted( [" foo ", "    bAR", "BaZ    "], key=lambda s: s.strip().upper())
# Out:
# ['    bAR', 'BaZ    ', ' foo ']

Sort list just ignoring whitespaces:

sorted( [" foo ", "    bAR", "BaZ    "], key=lambda s: s.strip())
# Out:
# ['BaZ    ', '    bAR', ' foo ']

Examples with map:

sorted( map( lambda s: s.strip().upper(), [" foo ", "    bAR", "BaZ    "]))
# Out:
# ['BAR', 'BAZ', 'FOO']

sorted( map( lambda s: s.strip(), [" foo ", "    bAR", "BaZ    "]))
# Out:
# ['BaZ', 'bAR', 'foo']

Examples with numerical lists:

my_list = [3, -4, -2, 5, 1, 7]
sorted( my_list, key=lambda x: abs(x))
# Out:
# [1, -2, 3, -4, 5, 7]

list( filter( lambda x: x>0, my_list))
# Out:
# [3, 5, 1, 7]

list( map( lambda x: abs(x), my_list))
# Out:
[3, 4, 2, 5, 1, 7]

One can call other functions (with/without arguments) from inside a lambda function.

def foo(msg):
    print(msg)

greet = lambda x = "hello world": foo(x)
greet()

prints:

hello world

This is useful because lambda may contain only one expression and by using a subsidiary function one can run multiple statements.

NOTE

Bear in mind that PEP-8 (the official Python style guide) does not recommend assigning lambdas to variables (as we did in the first two examples):

Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.

Yes:

def f(x): return 2*x

No:

f = lambda x: 2*x

The first form means that the name of the resulting function object is specifically f instead of the generic <lambda>. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Functions:
* Lambda Inline, Anonymous Functions

Table Of Contents
2 Filter
3 List
4 Functions
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve