# 11 Basic lambda Function Practice Exercises in Python

In this article, we’ll explore some basic lambda function practice exercises to help Python learners grasp the concept and its practical applications.

## Syntax of a Lambda Function

Lambda functions, also known as anonymous functions, are a powerful and concise way to create small, throwaway functions in Python. They are especially useful for situations where you need a simple function for a short period.

A lambda function in Python is defined using the `lambda` keyword, followed by one or more arguments, a colon `:`, and an expression. The expression is evaluated and returned as the result of the lambda function. Let’s start with a simple example:

```# A lambda function that adds two numbers
add = lambda x, y: x + y
print(result)
```
``8``

In this example, I have created a lambda function `add` that takes two arguments, `x` and `y`, and returns their sum.

Course for You: Learn Python in 100 days of coding

Okay, let’s now see some basic lambda function exercises in Python, I have tested all the codes listed in this article in Jupyter Notebook.

## Exercise 1: map() with Lambda

Using map() with a lambda function to square each element of a list.

```# Using map() with a lambda function to square each element of a list
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)
```
``[1, 4, 9, 16, 25]``

## Exercise 2: filter() with with Lambda

Using in-built function filter() with a lambda function filters even numbers from a list.

```# Using filter() with a lambda function to filter even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
```
``[2, 4, 6, 8]``

## Exercise 3: Sorting with Lambda

You can use lambda functions to define custom sorting criteria. In this case, we are sorting the list of tuples based on the second element (name). Below is an example code:

```# lambda function exercises in python: Sorting a list of tuples by the second element
scores = [(95, "Alice"), (89, "Bob"), (92, "Charlie")]
scores.sort(key=lambda x: x)
print(scores)
```
``[(95, 'Alice'), (89, 'Bob'), (92, 'Charlie')]``

Let’s use a lambda function to calculate grades for a list of scores. In this Python exercises you can also learn how to use lambda function with lists.

```# Calculate grades using lambda: basic lambda function python exercises
calculate_grade = lambda score: 'A' if score >= 90 else ('B' if score >= 80 else 'C')
scores = [88, 92, 78, 95, 86]
```
``['B', 'A', 'C', 'A', 'B']``

## Exercise 5: Combining Lists with Lambda

You can use lambda functions to combine elements from two lists. In this case, we’re using `map()` to add corresponding elements of `list1` and `list2`.

```# Combine two lists element-wise using a lambda function
list1 = [1, 2, 3]
list2 = [10, 20, 30]
combined = list(map(lambda x, y: x + y, list1, list2))
print(combined)
```
``[11, 22, 33]``

## Exercise 6: Lambda Functions in Dictionary Sorting

You can use lambda functions to sort dictionaries by their values. Here, we sort the dictionary `grades` by values in descending order.

```# Sorting a dictionary by values using a lambda function
grades = {'Alice': 88, 'Bob': 92, 'Charlie': 78, 'David': 95}
```
``{'David': 95, 'Bob': 92, 'Alice': 88, 'Charlie': 78}``

## Exercise 7: Lambda Functions with List Comprehensions

You can use lambda functions within list comprehensions for concise list transformations. In the below example code, we are returning doubles of each element in a list:

```numbers = [1, 2, 3, 4, 5]
doubled = [(lambda x: x * 2)(x) for x in numbers]
print(doubled)
```

## Exercise 8: Handling Multiple Arguments with Lambda

Lambda functions can handle multiple arguments, making them suitable for tasks like calculating the average of a list of numbers. Here, the lambda function `average` accepts a variable number of arguments and calculates the average.

```# Handling Multiple Arguments with Lambda function python exercises
average = lambda *args: sum(args) / len(args) if len(args) > 0 else 0
result = average(2, 4, 6, 8, 10)
print(result)
```
``6.0``

## Exercise 9: Recursive Lambda Functions

Although not a common use case, you can create recursive lambda functions to solve recursive problems. Below is an example that calculates the factorial of a number using a recursive lambda function.

Also Read:  Flask vs Django: Which One is Easier for Machine Learning?

In this example, the lambda function `factorial` calculates the factorial of a number using recursion.

```# lambda function exercises: Recursive Lambda Functions
factorial = lambda n: 1 if n == 0 else n * factorial(n - 1)
result = factorial(5)
print(result)  # Output: 120 (5!)
```
``120``

## Exercise 10: Sorting with Multiple Criteria

Lambda functions can be used for more complex sorting scenarios where multiple criteria are involved. In the below code, we are sorting a list of dictionaries based on two keys. This code sorts the list of dictionaries first by ‘age’ and then by ‘name’ when ages are equal.

```students = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 22}, {'name': 'Charlie', 'age': 25}]
sorted_students = sorted(students, key=lambda x: (x['age'], x['name']))
print(sorted_students)
```
``[{'name': 'Bob', 'age': 22}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 25}]``

## Exercise 11: Lambda Functions for Functional Programming

Lambda functions are a fundamental concept in functional programming. You can use them to create higher-order functions like `map`, `filter`, and `reduce`. Here’s an example using `reduce` to find the product of elements in a list:

```# Lambda Functions for Functional Programming
from functools import reduce

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

## Conclusion

Lambda functions are a handy tool in Python for creating small, one-time-use functions. By practicing these basic lambda function exercises, you can gain a better understanding of their utility and begin incorporating them into your Python code, which will help you in interviews or writing script time.

As you become more comfortable with lambda functions, you’ll discover even more ways to streamline your code and make it more expressive.

This is it for this article. If you have any questions or suggestions regarding this article, please please drop a comment below. If you want to learn Python quickly then this Udemy course is for you: Learn Python in 100 days of coding.

Also Read:  Convert Python Script to Compiler Executable (.exe File)