[Introduction to Python] Basic usage of lambda expressions

Article purpose

The same Python beginner as you should understand the basic usage of lambda expressions.

The other day, my senior asked me about the usage of lambda expressions, but I didn't use them so much and couldn't answer well, so I looked them up and summarized them. At that time, I referred to the following site. In fact, this article is for organizing my thoughts, so I think it's easier to understand if you read the linked article.

Qiita: Python lambda is easy to understand

What is a lambda expression?

The lambda expression is used to create an anonymous function. Intangible functions, as the name implies, are unnamed functions. Let's create a function that calculates the sum of two values, an ordinary function and an anonymous function, and compare the differences.

First is a normal function. Define the function with the function name as add.

#Ordinary function
def add(a, b):
  return a + b

#Call the function from the function name "add".
print(add(1, 2)) #==>3 is output

Next, let's do the same with an anonymous function. I'm defining an anonymous function and assigning that function object to a variable (add_lambda). ~~ When using an anonymous function, call a function object from a variable. ** Anonymous functions are assigned to variables because anonymous functions do not have a function name to call, so they cannot be used unless they are assigned to a variable **. ~~ This time, the anonymous function is assigned to the variable and used, but it is also possible to use the anonymous function without using the variable. (Thank you for pointing out @konandoiruasa.)

#Anonymous function object variable(add_lambda)Substitute in.
add_lambda = lambda x, y: x + y

#Call a function object from a variable.
print(add_lambda(1, 2)) #==>3 is output

As you can see, these two examples do the same thing. So why do you bother with lambda? This will be discussed next.

Why you need a lambda function

** The bottom line is that it can be easier to write. ** **

Now, I would like to explain with a concrete example when it can be easily described.

In Python, you can create a function that accepts a function as a function argument. As an example, consider a function (return_result) that displays the result of the received function.

### disp_function of result###
#Function as an argument(func)Arguments used in and func(*args)To receive
# func(args)Display the result of
def return_result(func, *args):
  return func(*args)

Let's compare the case of executing with a normal function and the case of executing with an anonymous function when a function that returns the sum of two is given as an argument to this return_result.

First, let's look at ordinary functions.

def add(a, b):
  return a + b

print(return_result(add ,1, 2)) #==>3 is displayed.

Now let's look at the case of using an anonymous function.

print(return_result(lambda x, y: x + y, 1, 2)) #==>3 is displayed.

Creating an anonymous function with lambda makes it easier to write because you don't have to define the function separately.

In this way, when using an anonymous function in a function (func) and a function (return_result) that takes arguments (* args) as arguments, the description can be simplified by the amount that the function definition is not required. However, if you want to use a complex function as func, you need to define the function separately instead of lambda.

How to use a lambda expression

The usage of lambda is as follows.

#lambda argument a,Argument b:Processing using arguments a and b
func_lambda = lambda a, b: a + b

More details are as follows. ** This is a screenshot of a part of the Python documentation. .. ** ** スクリーンショット 2020-01-06 13.49.51.png

Situations that are likely to be used frequently

I see articles that are often used in the map and filter functions.

Summary

lambda does not have much merit to use in complicated functions or normal functions, but it is convenient because it is easy to describe for functions that receive functions such as higher-order functions as arguments. .. .. That is my own conclusion.

Note (added as you pointed out): How to use anonymous functions without variables

sum_result = (lambda x, y: x+y)(1, 2) # sum_3 is assigned to result.

The reason why you can write like this is, according to the lambda document,

The expression lambda parameters: expression becomes a function object.

There is. Yes, a lambda expression is a function object !! So the (lambda x, y: x + y) part is a function object.

Therefore, it can be used as a function in the form of function object (actual argument) !! With this method, you can use anonymous functions once without using variables !! I did not know.

Reference

Python documentation Qiita: Python lambda is easy to understand

Recommended Posts

[Introduction to Python] Basic usage of lambda expressions
[Introduction to Python] Basic usage of the library matplotlib
Basic usage of Python f-string
[Introduction to Udemy Python 3 + Application] 58. Lambda
Introduction of Python
[Introduction to Python] Basic usage of the library scipy that you absolutely must know
Introduction of Python
[Road to intermediate Python] Use lambda expressions
[Introduction to Data Scientists] Basics of Python ♬
Basic grammar of Python3 system (how to use functions, closures, lambda functions)
[Introduction to Udemy Python 3 + Application] 26. Copy of dictionary
[Introduction to Udemy Python 3 + Application] 19. Copy of list
Basic usage of flask-classy
Usage of Python locals ()
Introduction to Python language
Basic usage of SQLAlchemy
Introduction to OpenCV (python)-(2)
Python Basic Course (Introduction)
Basic knowledge of Python
Summary of studying Python to use AWS Lambda
[Python] I was addicted to not saving internal variables of lambda expressions
[Chapter 5] Introduction to Python with 100 knocks of language processing
[Introduction to Udemy Python3 + Application] 53. Dictionary of keyword arguments
[Chapter 2] Introduction to Python with 100 knocks of language processing
[Introduction to Udemy Python3 + Application] 52. Tupleization of positional arguments
[Chapter 4] Introduction to Python with 100 knocks of language processing
[Python] Correct usage of map
Super basic usage of pytest
Introduction to Python Django (2) Win
[Introduction to cx_Oracle] Overview of cx_Oracle
Basic usage of PySimple GUI
Introduction of activities applying Python
Introduction to serial communication [Python]
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)
Basic usage of Pandas Summary
Sample usage of Python pickle
An introduction to Python Programming
[Python] Correct usage of join
How to use Python lambda
Introduction to Python For, While
[Introduction to Data Scientists] Basics of Python ♬ Functions and classes
[Raspi4; Introduction to Sound] Stable recording of sound input with python ♪
[2020/06 latest version] Basic usage of python dependency management tool poetry
[Introduction to Udemy Python 3 + Application] 31. Comments
Introduction to Ansible Part 2'Basic Grammar'
Introduction to Python Numerical Library NumPy
Practice! !! Introduction to Python (Type Hints)
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Udemy Python 3 + Application] 57. Decorator
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[Introduction to Python] How to parse JSON
[Lambda] [Python] Post to Twitter from Lambda!
[Introduction to Udemy Python 3 + Application] 56. Closure
Introduction to Protobuf-c (C language ⇔ Python)
[Introduction to Udemy Python3 + Application] 59. Generator
[Introduction to Python] Let's use pandas
Basic grammar of Python3 system (dictionary)
Introduction of python drawing package pygal
[Introduction to Udemy Python 3 + Application] Summary
Introduction to image analysis opencv python