How to use Python lambda

Introduction

When you hear lambda, you might think of AWS lambda, This time I'm talking about lambda, which means anonymous function in Python.

What is Python lambda?

In a nutshell, you can define a function without using a def statement.

I think that the def statement has the following structure.

def function(argument):
return expression

In lambda, you can write as follows.

function =lambda argument:formula

How to use

I will describe how to use this lambda.

def statement

First of all, I would like to write a program with a def statement without using lambda. Prepare a list with lowercase and uppercase alphabets as the content, You can use the capitalize function to correct all uppercase letters.

l = ['A', 'b', 'C', 'd', 'e', 'F', 'g']

def change_words(words, func):
    for word in words:
        print(func(word))

def sample_func(word):
    return word.capitalize()

change_words(l, sample_func)

In the change_words function The argument is set to func, which passes words and function. In the process inside, words are turned in a for loop and the value is put in func (). The content is to change the word according to the definition of func.

In the sample_func function It takes word as an argument, and inside the string capitalize () It is a process such as returning using a method to capitalize.

When you actually execute it, you can see that it is output in all uppercase letters.

A
B
C
D
E
F
G

lambda Let's write the above program using lambda.

l = ['A', 'b', 'C', 'd', 'e', 'F', 'g']

def change_words(words, func):
    for word in words:
        print(func(word))

#def sample_func(word):
#    return word.capitalize()
sample_func = lambda word: word.capitalize()

change_words(l, sample_func)

It is possible to write in one line like this. If you try it, you will get the same result.

Don't give a name to your lambda expression

This time, for the sake of clarity, the lambda expression I named it sample_func, but

Python coding convention PEP8 It is recommended that you use def when defining a function with a name.

Therefore, it is possible to write it directly and pass it as a function without giving it a name.

l = ['A', 'b', 'C', 'd', 'e', 'F', 'g']

def change_words(words, func):
    for word in words:
        print(func(word))

# def sample_func(word):
#    return word.capitalize()
# sample_func = lambda word: word.capitalize()

change_words(l, lambda word: word.capitalize())

With this description, you can use the function without defining it one by one. I think it will be a beautiful program.

More effectively

To feel the effect of lambda more Now let's add a function that corrects the alphabet to lowercase.

def statement

First, let's write it with a def statement.

l = ['A', 'b', 'C', 'd', 'e', 'F', 'g']

def change_words(words, func):
    for word in words:
        print(func(word))


def sample_func(word):
    return word.capitalize()

def sample_func2(word):
    return word.lower()

change_words(l, sample_func)

change_words(l, sample_func2)

A new function has been added with the name sample_func2.

When you actually execute it, lowercase alphabets are also output.

A
B
C
D
E
F
G
a
b
c
d
e
f
g

The contents of the sample_func2 function I just changed capitalize () to lower ().

However, it is troublesome to have to define each function and then write it.

lambda Therefore, it is easier to write in one line using lambda.

l = ['A', 'b', 'C', 'd', 'e', 'F', 'g']

def change_words(words, func):
    for word in words:
        print(func(word))

change_words(l, lambda word: word.capitalize())

change_words(l, lambda word: word.lower())

Even if you execute this, the same result will be output.

If you define function as an argument in () using lambda Because you don't have to define a function with def It makes it possible to write very efficient programs.

Postscript

Below, the content of your comments has been reflected in the article.

Let's combine with map and filter

Combine the lambda described above with the built-in functions map and filter It will be more efficient to use.

Let's use the map function here.

When actually combined with map The content that changes word according to the definition of func The change_words function no longer needs to be defined in def.

l = ['A', 'b', 'C', 'd', 'e', 'F', 'g']

change_words = map(lambda c: c.capitalize(), l)

print(list(change_words)

Use list comprehensions as much as possible

So far, I explained how to handle lambda and map, The book Effective Python recommends the use of list comprehensions instead. (* See item 7 on page 15 for details.)

The following is the program when using list comprehension notation.

l = ['A', 'b', 'C', 'd', 'e', 'F', 'g']

change_words = [c.capitalize() for c in l]

print(change_words)

In my book, there are two main reasons why I recommend list comprehension.

The first is readability.

List comprehensions use extra lambda expressions compared to the built-in functions map and filter It is stated to be clear because it is not needed.

Certainly, even if you look at the above program, the list comprehension notation is better It looks neat and I think it's easy to describe.

Secondly, list comprehension makes it easier to extract elements from the input list.

For example, suppose you want to output only uppercase B from a list.

List comprehensions are possible by simply adding a conditional statement after the loop.

l = ['A', 'b', 'C', 'd', 'e', 'F', 'g']

change_words = [c.capitalize() for c in l if c == 'b']

print(change_words)

However, in the case of map, it cannot be described without the help of filter.

l = ['A', 'b', 'C', 'd', 'e', 'F', 'g']

change_words = map(lambda c: c.capitalize(), filter(lambda c: c == 'b', l))

print(list(change_words))

This is possible with filter, but it's not a very readable program.

From the above points of view, list comprehension is better than map and filter.

in conclusion

At first, it was only a guide for lambda, but after receiving comments, I was able to delve into maps, filters, and even list comprehensions. Thank you very much.

Recommended Posts

How to use Python lambda
python3: How to use bottle (2)
[Python] How to use list 1
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
Python: How to use async with
[Python] How to use Pandas Series
How to use Mysql in python
How to use OpenPose's Python API
How to use ChemSpider in Python
How to use FTP with Python
How to use PubChem in Python
How to use python zip function
[Python] How to use Typetalk API
How to use xml.etree.ElementTree
How to use Python-shell
[Python] Summary of how to use pandas
[Introduction to Python] How to use class in Python?
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to install Python
How to use Pandas 2
How to install and use pandas_datareader [Python]
How to use Virtualenv
How to use pytest_report_header
[python] How to use __command__, function explanation
How to install python
How to use Bio.Phylo
How to use SymPy
[Python] How to use import sys sys.argv
How to use x-means
How to use WikiExtractor.py
How to use IPython
Memorandum on how to use gremlin python
How to use virtualenv
[Python2.7] Summary of how to use unittest
How to use Matplotlib
How to access RDS from Lambda (python)
How to use iptables
python: How to use locals () and globals ()
How to use numpy
How to use __slots__ in Python class
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use "deque" for Python data
How to use python-kabusapi
How to use Python zip and enumerate
Summary of how to use Python list
[Road to intermediate Python] Use lambda expressions
How to use regular expressions in Python
How to use return
How to use dotenv