Blog

Filter posts by Category Or Tag of the Blog section!

Functional programming with lambda expressions and higher-order functions in python

Saturday, 03 June 2023

If you have worked with programming languages, you know that Functional programming is a programming paradigm that emphasizes the use of pure functions, immutable data, and function composition. Lambda expressions and higher-order functions are key concepts in functional programming. In Python, you can use lambda expressions and higher-order functions to write functional code.

 

A lambda expression is a small anonymous function that can be used inline. It allows you to create functions without explicitly defining them using the def keyword. Lambda expressions are often used in conjunction with higher-order functions.

 

A higher-order function is a function that takes one or more functions as arguments and/or returns a function as its result. It treats functions as first-class citizens, allowing you to pass functions as arguments and manipulate them. Interesting?

 

Here's an example that demonstrates the use of lambda expressions and higher-order functions in Python:

 

# Example 1: Lambda expression
# Create a lambda function that doubles a number
double = lambda x: x * 2
print(double(5))  # Output: 10

# Example 2: Higher-order function
# Create a function that applies a given function to each element of a list
def apply_function_to_list(lst, func):
    return [func(x) for x in lst]

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

# Use the higher-order function to double each number in the list
result = apply_function_to_list(numbers, lambda x: x * 2)
print(result)  # Output: [2, 4, 6, 8, 10]

 

In the first example, we define a lambda expression that doubles a number. We assign this lambda expression to the variable double and then call it with an argument of 5. The lambda function multiplies the argument by 2 and returns the result, which is then printed.

 

In the second example, we define a higher-order function apply_function_to_list that takes a list lst and a function func. It applies the given function to each element of the list using list comprehension and returns the resulting list. We use a lambda expression as the func argument to double each number in the numbers list.

 

These examples demonstrate how lambda expressions and higher-order functions can be used together to write concise and functional code in Python.

 

Category: Software

Tags: Python

comments powered by Disqus