free geoip
7

Python Lambda Functions Practice

In this tutorial, we will explore Python lambda functions — also known as anonymous functions — and learn how to…

In this tutorial, we will explore Python lambda functions — also known as anonymous functions — and learn how to use them effectively in real-world examples. Lambda functions are a concise way to define small, one-line functions without using the standard def keyword. This guide will cover the syntax, use cases, and several practical exercises to strengthen your understanding of lambda expressions in Python.

Python Lambda Functions Practice

What is a Lambda Function in Python?

A lambda function is a small anonymous function that can take any number of arguments but can only have one expression. The syntax is:

lambda arguments: expression

For example:

add = lambda x, y: x + y
print(add(5, 3))  # Output: 8

In the above example, the lambda function performs the same role as a normal function but in a shorter way. You can think of it as a quick function for simple tasks.

Why Use Lambda Functions?

Lambda functions are often used when you need a short function for a brief period of time — especially when passing functions as arguments to higher-order functions like map(), filter(), or sorted(). Using lambda helps make your code more compact and expressive.

Common use cases:

  • Sorting data based on custom rules
  • Filtering lists or collections
  • Mapping or transforming data
  • Using inside functions like reduce() or GUI callbacks

Example 1: Using Lambda with map()

The map() function applies a given function to all items in a list. With lambda, we can simplify the process:

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

Here, instead of defining a separate function to square numbers, we used a lambda expression inside the map() function.

Example 2: Using Lambda with filter()

The filter() function filters a list based on a condition. Let’s find all even numbers from a list:

numbers = [10, 15, 20, 25, 30, 35]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
# Output: [10, 20, 30]

The lambda function here checks whether each element is even. The filter() function returns only those elements for which the condition is True.

Example 3: Using Lambda with sorted()

Lambda functions are very useful when sorting lists or tuples with custom keys.

students = [
    ('Alice', 23),
    ('Bob', 20),
    ('Charlie', 25)
]

# Sort by age
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
# Output: [('Bob', 20), ('Alice', 23), ('Charlie', 25)]

Instead of defining a separate function to extract the age, we used a lambda directly inside sorted().

Example 4: Combining map(), filter(), and lambda

Let’s combine multiple functions to process data efficiently.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Square only even numbers
result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))
print(result)
# Output: [4, 16, 36, 64]

This example shows how lambda functions can be chained for concise, powerful data processing.

Example 5: Using Lambda Inside Functions

You can define a lambda inside another function to create custom operations dynamically.

def power_function(n):
    return lambda x: x ** n

square = power_function(2)
cube = power_function(3)

print(square(5))  # Output: 25
print(cube(5))    # Output: 125

This example demonstrates how lambdas can help generate other functions programmatically.

Example 6: Using Lambda with reduce()

The reduce() function from the functools module allows you to reduce a list to a single value by applying a function cumulatively.

from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)
# Output: 120

Here, the lambda multiplies elements one by one, reducing the list to a single product value.

Example 7: Real-World Case — Sorting Dictionary by Values

scores = {'Alice': 85, 'Bob': 90, 'Charlie': 82}

sorted_scores = dict(sorted(scores.items(), key=lambda item: item[1], reverse=True))
print(sorted_scores)
# Output: {'Bob': 90, 'Alice': 85, 'Charlie': 82}

Lambdas make it easy to sort dictionary data structures without defining extra helper functions.

Tips for Using Lambda Functions Effectively

  • Use lambdas for short, simple expressions — not complex logic.
  • If your lambda becomes longer than one line, consider defining a normal function.
  • Combine with map(), filter(), sorted(), or reduce() for maximum productivity.
  • Remember, lambdas cannot contain statements, only expressions.

Practice Exercise: Try It Yourself

  1. Write a lambda to find the maximum of two numbers.
  2. Use map() with lambda to cube all numbers in a list.
  3. Filter out words shorter than 5 characters from a list of words.
  4. Sort a list of dictionaries by a key using lambda.
  5. Use reduce() and lambda to sum a list of numbers.

Practicing these exercises will help you understand how to apply lambda functions in different programming situations.

Conclusion

Python lambda functions are a powerful feature that allows developers to write cleaner and more concise code. They are especially useful for small tasks, one-time use functions, and functional programming approaches. By mastering lambda expressions, you can simplify your code structure and improve readability.

Start experimenting with the examples provided above, and soon you’ll be able to use lambda functions confidently in your Python projects.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *