[PYTHON] Anonymous and map functions

I'll forget about anonymous functions soon, so make a note for myself

Anonymous function (lambda expression)

Used for code simplification

def calc_multi(a, b):
    return a * b

calc_multi(3, 10)

#output
# 30

This process can be written as The point is lambda a, b:, which corresponds to the function name (a, b) Describe the processing of the function (return a * b here) separated by:

(lambda a, b: a * b)(3, 10)

#output
# 30

map function

Lambda expressions are often used when you want to execute some function on an element such as a list Use ** map function (higher-order function) ** when you want to process an element A function that uses a function as an argument or return value, and is used when you want to process or operate on each element.

def calc_double(x) :
    return x * 2

for num in [1, 2, 3, 4]:
    print(calc_double(num))

#output
# 2
# 4
# 6
# 8

If you use the map function, you can process the list as it is

list(map(calc_double, [1, 2, 3, 4]))

#output
# [2,4,6,8]

Furthermore, if you use an anonymous function, you can write as follows

list(map(lambda x : x * 2, [1, 2, 3, 4]))

#output
# [2,4,6,8]

Recommended Posts

Anonymous and map functions
Higher-order functions and decorators
Ruby, Python and map
matplotlib gallery and color map
Python 3 sorted and comparison functions
Class inheritance and super functions
Python higher-order functions and comprehensions
About python dict and sorted functions
Formulas and functions (updated as appropriate)
GCP: Link Functions and Pub / Sub
map
python string processing map and lambda
Understand Armijo's rules and convex functions
Tips for replacing and debugging functions
[Introduction to Data Scientists] Basics of Python ♬ Functions and anonymous functions, etc.
Graph trigonometric functions with numpy and matplotlib
Ramen map creation with Scrapy and Django
Use Python and MeCab with Azure Functions
Correspondence between Python built-in functions and Rust