Anonymous functions in python

Understanding Lambda Functions in Python | The Beauty of Anonymous Functions

In this Python tutorial, we will discuss Lambda functions in Python. Also, we will see, what is the use of the lambda function in Python. I will also explain, what is an anonymous function in Python.

What is a Lambda Function in Python?

Lambda functions, also known as anonymous functions, are a feature in Python that allows for the creation of small, simple functions in a concise manner. Unlike the traditional functions defined using the def keyword, lambda functions are defined using the lambda keyword, and they don’t have a name. This is why they are referred to as anonymous functions.

Syntax:

lambda arguments: expression 

This means a lambda function can take any number of arguments, but can only have one expression.

Example:

multiply = lambda x, y: x * y print(multiply(5, 3)) # Output: 15 

In the example above, we create a lambda function that takes two arguments, x and y , and returns their product. We then assign this lambda function to a variable called multiply and call it just like a regular function.

Читайте также:  Присвоить тип переменной python

what is lambda function in python

When and Why Use Lambda Functions in Python?

Lambda functions in Python are particularly useful when you need a small function for a short period of time and don’t want to formally define it. They’re concise and can be written in a single line. This makes them perfect candidates for scenarios where a function is only used once or for a short snippet of code.

Common use cases include:

  1. Sorting and Filtering: Lambda functions can be used as the key function while sorting or as the function to filter data.
  2. Functional Programming: Python supports functional programming concepts like map() , filter() , and reduce() where lambda functions are handy.

Examples

1. Sorting with Lambda:

data = [('apple', 3), ('banana', 1), ('orange', 4), ('grapes', 2)] # Sort by the second element in each tuple sorted_data = sorted(data, key=lambda x: x[1]) print(sorted_data) # Output: [('banana', 1), ('grapes', 2), ('apple', 3), ('orange', 4)] 

You can see the output like below:

use of lambda function in python

2. Filtering with Lambda:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Get the odd numbers odd_numbers = list(filter(lambda x: x % 2 != 0, numbers)) print(odd_numbers) # Output: [1, 3, 5, 7, 9] 

3. Using Map with Lambda:

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

Understanding Anonymous Functions in Python

As we mentioned earlier, lambda functions are anonymous. This means they don’t have a name associated with them. They are useful when you need a function for a short duration and do not want to define it formally.

This concept is especially useful in functional programming. Here’s an example where we use an anonymous lambda function in Python inside the filter() function without assigning it to a variable.

# Filter out numbers less than 5 numbers = [2, 8, 3, 5, 7, 9, 1] filtered_numbers = list(filter(lambda x: x < 5, numbers)) print(filtered_numbers) # Output: [2, 3, 1]

You can see the output below:

anonymous function in python

Conclusion

Lambda functions or anonymous functions in Python are powerful tools for writing cleaner, more concise code, especially for short, simple functions. They are versatile and can be used in various scenarios like sorting, filtering, and other functional programming paradigms. However, keep in mind that while lambda functions make code shorter, overuse can lead to less readable code.

You may like the following Python tutorials:

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Python Anonymous Function – How to Use Lambda Functions

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Python Anonymous Function – How to Use Lambda Functions

You can use functions in programming to store a piece of code that can be invoked when needed. This prevents you from retyping the same logic every time you need that code.

In this article, you'll learn how to create and use anonymous functions in Python. They are also called lambda functions.

We'll begin with a quick overview of how regular functions are created in Python. Then you'll learn the syntax and practical applications of anonymous functions in Python.

You'll also see some of the differences between lambda and regular functions in Python, and when to use lambda functions.

How to Use Functions in Python

Functions prevent you from reinventing the wheel when certain logic is required multiple times.

first_addition = 2+3 print(first_addition) # 5 second_addition = 3+5 print(second_addition) # 8

We had to recreate the logic for addition multiple times in different variables. Imagine if you had to do this a hundred times.

With a function, you can create the logic once and reuse it as much as you want to. Here's an example in Python:

def add_numbers(a,b): return a + b print(add_numbers(2,3)) # 5 print(add_numbers(3,5)) # 8 print(add_numbers(5,7)) # 12

Using the def keyword, we created a function called add_numbers(a,b) . It takes two parameters – a and b . The function returns the sum of a and b .

So to use the logic multiple times, we just had to call the function and pass in different parameters for different operations:

print(add_numbers(2,3)) # 5 print(add_numbers(3,5)) # 8 print(add_numbers(5,7)) # 12 

Now let's take a look at anonymous/lambda functions in Python.

How to Use Lambda Functions in Python

An anonymous function in Python is a function without a name. It can be immediately invoked or stored in a variable.

Anonymous functions in Python are also known as lambda functions.

Here's the syntax for creating a lambda function in Python:

lambda parameter(s) : expression

There are three values that define a lambda function as seen in the syntax above:

  • A lambda function is created using the lambda keyword.
  • The keyword is followed by one or many parameters.
  • Lastly, an expression is provided for the function. This is the part of the code that gets executed/returned.

The parameter(s) and expression are separated by a colon.

add_numbers = lambda a,b : a + b print(add_numbers(2,3)) # 5 

In the code above, we created a lambda function with two parameters – a and b . The function returns the sum of the parameters.

Note that the function has no name. We assigned the lambda function to a variable called add_numbers so that we can easily invoke the function through the variable.

Without assigning a lambda function to a variable, you'd have something like this:

print(lambda a,b : a + b) # at 0x7f757922fb00>

The code above simply returns a lambda object in the console.

You can immediately call a lambda function using parenthesis:

When the code above is printed, you'll get 5 returned.

What Is the Difference Between Lambda and Regular Functions in Python?

Here are some differences between lambda functions and regular functions in Python:

Lambda functions Regular functions
Defined using the lambda keyword Defined using the def keyword
Can be written in one line Requires more than one line of code
No return statement required Return statement must be defined when returning values
Can be used anonymously Regular functions must be given a name

When to Use a Lambda Function in Python

Although you can use both regular functions and lambda functions to achieve the same results, here are some of the reasons why you might pick a lambda function:

First of all, you can use a lambda function when you need a function that'll be used just once. This is especially useful when working with functions like map , reduce , filter . Consider the code below:

def double_number(n): return n + n numbers = [1, 3, 5, 7, 9] double_result = map(double_number, numbers) print(list(double_result)) # [2, 6, 10, 14, 18]

In the code above, we created a regular function called double_number which doubles the value of a number.

Although the function was passed in as a parameter to the map function — map(double_number, numbers) , we had to write the logic before using it.

With lambda functions, you can do this:

numbers = [1, 3, 5, 7, 9] double_result = map(lambda x : x+x, numbers) print(list(double_result)) # [2, 6, 10, 14, 18]

As you can see above, we just passed a lambda function — lambda x : x+x — as a parameter to the map function: map(lambda x : x+x, numbers) .

We were able to achieve the same result with fewer lines of code. There was no need for defining a function first before use.

You can also use a lambda function when you need a function that should be invoked immediately. As you can see in the example in the previous point, we first defined the regular function before using it. Lambda functions can be invoked immediately after creating them.

Finally, lambdas are useful when you want to use a function inside a function. Or when you want to create a function that returns a function.

Summary

In this article, we talked about lambda functions in Python. There are functions without a name and can be executed with a single line of code.

We saw how to use regular functions in Python with some examples.

We then saw the syntax and a practical example of using lambda functions.

Lastly, we talked about the differences between lambda functions and regular functions in Python, and when to use lambda functions.

Источник

Оцените статью