Lambda Functions

Earlier we quickly covered the most common way of defining functions, the def statement. You'll likely come across another way of defining short, one-off functions with the lambda statement. It looks something like this

add = lambda x, y: x + y
add(1, 2)

add(1, 2)

# 3

This lambda function is roughly equivalent to

def add(x, y):
    return x + y

So why would you ever want to use such a thing? Primarily, it comes down to the fact that everything is an object in Python, even functions themselves! That means that functions can be passed as arguments to functions.

As an example of this, suppose we have some data stored in a list of dictionaries:

data = [{'first':'Guido', 'last':'Van Rossum', 'YOB':1956},
        {'first':'Grace', 'last':'Hopper',     'YOB':1906},
        {'first':'Alan',  'last':'Turing',     'YOB':1912}]

Now suppose we want to sort this data. Python has a sorted function that does this:

sorted([2,4,3,5,1,6])

# [1, 2, 3, 4, 5, 6]

But dictionaries are not orderable: we need a way to tell the function how to sort our data. We can do this by specifying the key function, a function which given an item returns the sorting key for that item:

# sort alphabetically by first name
sorted(data, key=lambda item: item['first'])

[{'YOB': 1912, 'first': 'Alan', 'last': 'Turing'},
 {'YOB': 1906, 'first': 'Grace', 'last': 'Hopper'},
 {'YOB': 1956, 'first': 'Guido', 'last': 'Van Rossum'}]
# sort by year of birth
sorted(data, key=lambda item: item['YOB'])

Output

[{'YOB': 1906, 'first': 'Grace', 'last': 'Hopper'},
 {'YOB': 1912, 'first': 'Alan', 'last': 'Turing'},
 {'YOB': 1956, 'first': 'Guido', 'last': 'Van Rossum'}]

While these key functions could certainly be created by the normal, def syntax, the lambda syntax is convenient for such short one-off functions like these.

Last updated