coding180 icon
Coding180
Lambda Functions in Python: A Beginner's Guide

Lambda Functions in Python: A Beginner's Guide

Home > Tutorials > Python for beginners > Functions


Lambda functions, also known as anonymous functions, are a type of function that can be defined on the fly without needing to be assigned a name. They are a powerful feature in Python and can be used in many different contexts. In this guide, we will explore what lambda functions are, when to use them, and how to use them in common programming scenarios.

What are Lambda Functions?

A lambda function is a small, anonymous function that can be defined in a single line of code. Unlike normal functions, they do not require a name or a return statement. They are often used as arguments for higher-order functions (functions that take other functions as arguments), such as map() and filter(). Here's an example:

square = lambda x: x**2
print(square(5))  # Output: 25

This lambda function takes one argument (x) and returns the square of that argument. It is equivalent to the following normal function:

def square(x):
    return x**2

The two functions are essentially the same thing, but the lambda function is defined in a more concise way.

When to Use Lambda Functions

Lambda functions are most commonly used in situations where you need a simple function that will only be used once. This could include tasks like filtering data, sorting lists, or performing simple calculations. They are particularly useful when working with higher-order functions, as they allow you to define custom behavior on the fly without needing to write a separate function.

Simple Lambda Functions for Sorting and Filtering Data

One common use case for lambda functions is filtering data. The filter() function can be used to select elements from a list that satisfy a certain condition. Here's an example that uses a lambda function to filter out all of the odd numbers from a list:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(filtered_numbers)  
# Output: [2, 4, 6, 8, 10]

The lambda function in this example takes one argument (x) and returns True if it is even and False otherwise. The filter() function then uses this function to select only the even numbers from the original list.

Sorting data is another common use case for lambda functions. The sorted() function can be used to sort a list according to some criterion. Here's an example that uses a lambda function to sort a list of names alphabetically:

names = ["Alice", "Bob", "Charlie", "Dave", "Eve"]
sorted_names = sorted(names, key=lambda name: name.lower())
print(sorted_names)  
# Output: ['Alice', 'Bob', 'Charlie', 'Dave', 'Eve']

The lambda function in this example takes one argument (name) and returns the lowercase version of that argument. The sorted() function then uses this function to sort the list of names alphabetically (ignoring case).

Combining Lambda Functions with Built-In Functions like map() and filter()

Lambda functions are often used in combination with built-in functions like map() and filter(). These higher-order functions take other functions as arguments and apply them to elements in a list. Here's an example that uses a lambda function with map() to calculate the squares of all the numbers in a list:

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)  # Output: [1, 4, 9, 16, 25]

The lambda function in this example takes one argument (x) and returns the square of that argument. The map() function then applies this function to each element in the list of numbers.

Here's another example that uses a lambda function with filter() to select only the even numbers from a list:

numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # Output: [2, 4]

The lambda function in this example takes one argument (x) and returns True if it is even and False otherwise. The filter() function then uses this function to select only the even numbers from the original list.

Exercises

Practice using lambda functions by trying the following exercises:

  1. Write a lambda function that takes two arguments (a and b) and returns their sum.
  2. Use a lambda function with the sorted() function to sort a list of numbers in descending order.
  3. Use a lambda function with the map() function to convert a list of strings to uppercase.
# Exercise 1
sum_lambda = lambda a, b: a + b
print(sum_lambda(2, 3)) 

# Exercise 2
numbers = [10, 4, -2, 7, 3]
sorted_numbers = sorted(numbers, reverse=True, key=lambda x: x)
print(sorted_numbers) 

# Exercise 3
strings = ["hello", "world", "python"]
uppercase_strings = list(map(lambda s: s.upper(), strings))
print(uppercase_strings) 

In the first exercise, we define a lambda function that takes two arguments and returns their sum. We then call this function with the arguments 2 and 3, which should return 5.

In the second exercise, we use a lambda function with the sorted() function to sort a list of numbers in descending order. The lambda function simply returns each element in the list, so the sorting is done based on the default behavior of sorted(), which is to sort in ascending order. We pass the reverse=True argument to sort the list in descending order instead.

In the third exercise, we use a lambda function with the map() function to convert a list of strings to uppercase. The lambda function takes one argument (s) and returns the uppercase version of that argument. The map() function then applies this function to each element in the list of strings.

Conclusion

Lambda functions are a powerful feature in Python that allow you to define simple functions on the fly without needing to assign a name. They are most commonly used in situations where you need a simple function that will only be used once, such as filtering data or performing simple calculations. When combined with higher-order functions like map() and filter(), they provide a concise and powerful way to manipulate data in Python.


user

Robort Gabriel

Lagos, Nigeria

Freelance Web Developer, Native Android Developer, and Coding Tutor.

Skills
  • UI / UX
  • JavaScript
  • Python
  • PHP
  • Kotlin
  • Java
  • Bootrap
  • Android
  • Laravel