Skip to main content
HomeAbout PythonLearn Python

Python lambda Tutorial

Learn a quicker way of writing functions on the fly with lambda functions.
Aug 2020  · 3 min read

You can write your very own Python functions using the def keyword, function headers, docstrings, and function bodies. However, there's a quicker way to write functions on the fly, and these are called lambda functions because you use the keyword lambda.

Some function definitions are simple enough that they can be converted to a lambda function. By doing this, you write fewer lines of code, which is pretty awesome and will come in handy, especially when you're writing and maintaining big programs.

lambda Function

Here we rewrite our function raise_to_power as a lambda function. After the keyword lambda, we specify the names of the arguments; then, we use a colon followed by the expression that specifies what we wish the function to return.

raise_to_power = lambda x, y: x ** y

raise_to_power(2, 3)
8

As mentioned, the lambda functions allow you to write functions in a quick and dirty way, so we wouldn't advise you to use them all the time, but there are situations when they come in handy, like the example below.

map() and lambda Function

The map function takes two arguments, a function and a sequence such as a list and applies the function over all the elements of the sequence. We can pass lambda function to the map without even naming them, and in this case, we refer to them as anonymous functions.

In this example, we use map() on the lambda function, which squares all elements of the list, and we store the result in square_all.

nums = [48, 6, 9, 21, 1]

square_all = map(lambda num: num ** 2, nums)

print(square_all)
<map object at 0x103e065c0>

Printing square_all reveals that its a map object, so to see what it returns, we use list to turn it into a list and print the result.

print(list(square_all))
[2304, 36, 81, 441, 1]

Interactive Example of Writing a lambda Function

The below function echo_word takes 2 parameters: a string value, word1, and an integer value echo. It returns a string that is a concatenation of echo copies of word1.

You will convert the above simple function into a lambda function.

def echo_word(word1, echo):
    """Concatenate echo copies of word1."""
    words = word1 * echo
    return words

In the following example, you will:

  • Define a lambda function echo_word using the variables word1 and echo. Replicate what the original function definition for echo_word() does above.
  • Call echo_word() with the string argument 'hey' and the value 5, in that order. Assign the call to result. Finally, print the result variable.
# Define echo_word as a lambda function: echo_word
echo_word = (lambda word1, echo: word1 * echo)

# Call echo_word: result
result = echo_word('hey', 5)

# Print result
print(result)

When we run the above code, it produces the following result:

heyheyheyheyhey

Try it for yourself.

To learn more about Lambda functions, please see this video from our course Python Data Science Toolbox (Part 1).

This content is taken from DataCamp’s Python Data Science Toolbox (Part 1) course by Hugo Bowne-Anderson.

Check out DataCamp's Python Functions Tutorial.

Topics

Learn more about Python

Certification available

Course

Python Data Science Toolbox (Part 1)

3 hr
399.5K
Learn the art of writing your own functions in Python, as well as key concepts like scoping and error handling.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Mastering the Pandas .explode() Method: A Comprehensive Guide

Learn all you need to know about the pandas .explode() method, covering single and multiple columns, handling nested data, and common pitfalls with practical Python code examples.
Adel Nehme's photo

Adel Nehme

5 min

Python NaN: 4 Ways to Check for Missing Values in Python

Explore 4 ways to detect NaN values in Python, using NumPy and Pandas. Learn key differences between NaN and None to clean and analyze data efficiently.
Adel Nehme's photo

Adel Nehme

5 min

Seaborn Heatmaps: A Guide to Data Visualization

Learn how to create eye-catching Seaborn heatmaps
Joleen Bothma's photo

Joleen Bothma

9 min

Test-Driven Development in Python: A Beginner's Guide

Dive into test-driven development (TDD) with our comprehensive Python tutorial. Learn how to write robust tests before coding with practical examples.
Amina Edmunds's photo

Amina Edmunds

7 min

Exponents in Python: A Comprehensive Guide for Beginners

Master exponents in Python using various methods, from built-in functions to powerful libraries like NumPy, and leverage them in real-world scenarios to gain a deeper understanding.
Satyam Tripathi's photo

Satyam Tripathi

9 min

Python Linked Lists: Tutorial With Examples

Learn everything you need to know about linked lists: when to use them, their types, and implementation in Python.
Natassha Selvaraj's photo

Natassha Selvaraj

9 min

See MoreSee More