w3resource

Python Lambda Functions: A Practical Guide

Introduction to Python Lambda Functions

Lambda functions in Python are small, anonymous functions defined with the 'lambda' keyword. They are useful for creating simple functions without needing to formally define a function using 'def'. This tutorial will guide you through various examples of using lambda functions, focusing on practical usage.

Consider the following function:

Code:

def func(a): return a + 1
print(func(5)) # Output 6

The same function can be defined using lambda expression as follows:

Code:

func = lambda a: a + 1
print(func(5)) #Output 6

Both functions are the same. Note that lambda does not include a return statement. The right expression is the implicit return value. Lambda functions need not to be assigned to any variable.

Example 1: Basic Lambda Function

This example demonstrates a simple lambda function that adds 10 to a given number. Lambda functions are ideal for small, single-use functions like this.

Code:

# A basic lambda function that adds 10 to a given number
add_ten = lambda x: x + 100

# Using the lambda function
result = add_ten(25)  # Output: 125
print(result) 

Explanation:

  • Lambda Function: 'lambda x: x + 100' creates an anonymous function that takes one argument 'x' and returns 'x + 100'.
  • Usage: We assign the lambda function to the variable ‘add_ten’, then use it to add 100 to the number 25.

Example 2: Lambda Function with Multiple Arguments

This example shows a lambda function with multiple arguments, which multiplies two numbers. It highlights how lambda functions can handle simple operations with more than one input.

Code:

# A lambda function that multiplies two numbers
multiply = lambda x, y: x * y

# Using the lambda function
result = multiply(5, 3)  # Output: 15
print(result)

Explanation:

  • Lambda Function: 'lambda x, y: x * y' defines a function that takes two arguments, 'x' and 'y', and returns their product.
  • Usage: We use the lambda function to multiply 5 and 3, resulting in 15.

Example 3: Lambda Function with 'map()'

This example demonstrates using a lambda function with 'map()' to apply an operation to each element in a list, specifically squaring each number.

Code:

# A list of numbers
numbers = [1, 2, 3, 4, 5]

# Using map() with a lambda function to square each number in the list
squared_numbers = list(map(lambda x: x ** 2, numbers))

# Output: [1, 4, 9, 16, 25]
print(squared_numbers)

Explanation:

  • Lambda Function: 'lambda x: x ** 2' defines a function that squares its input.
  • 'map()' Function: Applies the lambda function to each element in the 'numbers' list.
  • Usage: The 'map()' function returns a map object, which we convert to a list of squared numbers.

Example 4: Lambda Function with 'filter()'

This example shows how to use a lambda function with filter() to select elements from a list that meet a certain condition—in this case, filtering out even numbers.

Code:

# A list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using filter() with a lambda function to filter out even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

# Output: [2, 4, 6, 8, 10]
print(even_numbers)

Explanation:

  • Lambda Function: 'lambda x: x % 2 == 0' defines a function that returns 'True' if 'x' is even.
  • 'filter()' Function: Filters the numbers list, returning only the even numbers.
  • Usage: The 'filter()' function returns a filter object, which we convert to a list of even numbers.

Example 5: Lambda Function with 'reduce()'

This example demonstrates using a lambda function with ‘reduce()’ to perform a cumulative operation on a list of elements, specifically calculating the product of all numbers.

Code:

from functools import reduce

# A list of numbers
numbers = [1, 2, 3, 4, 5]

# Using reduce() with a lambda function to calculate the product of all numbers
product = reduce(lambda x, y: x * y, numbers)

# Output: 120
print(product)

Explanation:

  • Lambda Function: 'lambda x, y: x * y' multiplies two numbers.
  • 'reduce()' Function: Applies the lambda function cumulatively to the items in the 'numbers' list, reducing them to a single value.
  • Usage: The 'reduce()' function returns the product of all numbers in the list.

Example 6: Lambda Function in Sorting

This example illustrates using a lambda function with sorted() to sort a list of tuples by a specific element—in this case, sorting people by age.

Code:

# A list of tuples representing (name, age)
people = [('Flavienne', 30), ('Zalmon', 25), ('Katerina', 35)]

# Using sorted() with a lambda function to sort by age
sorted_people = sorted(people, key=lambda person: person[1])

# Output: [('Flavienne', 25), ('Zalmon', 30), ('Katerina', 35)]
print(sorted_people)

Explanation:

  • Lambda Function: 'lambda person: person[1]' extracts the second element (age) from each tuple.
  • 'sorted()' Function: Sorts the 'people' list based on the age of each person.
  • Usage: The 'sorted()' function returns a new list of tuples sorted by age.

Example 7: Lambda Function in Dictionary Operations

This example demonstrates using a lambda function with ‘max()’ to find the key associated with the highest value in a dictionary, such as identifying the most expensive item.

Code:

# A dictionary of items and their prices
prices = {'apple': 2, 'banana': 1, 'cherry': 3}

# Using max() with a lambda function to find the most expensive item
most_expensive = max(prices, key=lambda item: prices[item])

# Output: 'cherry'
print(most_expensive)

Explanation:

  • Lambda Function: 'lambda item: prices[item]' returns the price of the item.
  • 'max()' Function: Finds the item with the highest price.
  • Usage: The 'max()' function returns the key (item) associated with the maximum value (price) in the dictionary.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python/python-lambda-functions-with-examples.php