lambda

Uppercase 1


l = ['Apple', 'banana', 'orange', 'Strawberry', 'cherry']

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

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

change_words(capit_func, l)

Execution result of 1 with a capital letter at the beginning


Apple
Banana
Orange
Strawberry
Cherry

The capi_func function is a function that capitalizes the beginning of the argument word. If you use lambda for this, you can reduce the amount of code.

Uppercase 2


l = ['Apple', 'banana', 'orange', 'Strawberry', 'cherry']

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

capit_func = lambda word: word.capitalize()

change_words(capit_func, l)

Bother Without defining capit_func It is also possible to write directly in the argument of the change_words function, It is possible to further reduce the amount of code.

Uppercase 3


l = ['Apple', 'banana', 'orange', 'Strawberry', 'cherry']

def change_words(func, words):
    for word in words:
        print(func(word))
        
change_words(lambda word: word.capitalize(), l)

This lambda is The function is not only the capit_func function It is effective when multiple functions are required.

Multiple functions


l = ['Apple', 'banana', 'orange', 'Strawberry', 'cherry']

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

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

Execution result of multiple functions


Apple
Banana
Orange
Strawberry
Cherry
apple
banana
orange
strawberry
cherry

if, If you don't use lambda

Multiple functions 2


l = ['Apple', 'banana', 'orange', 'Strawberry', 'cherry']

def change_words(func, words):
    for word in words:
        print(func(word))
        
def capit_func(word):
    return word.capitalize()

def low_func(word):
    return word.lower()
    
change_words(capit_func, l)
change_words(low_func, l)

Must be written. It is necessary to define two functions, capit_func function and low_func function.

Recommended Posts

lambda
Lambda expression
python3x: lambda function
LoL ~ Lambda operate Lambda ~
lambda expression memo
Make Lambda Layers with Lambda
RDS tutorial on Lambda
A python lambda expression ...
Run mysqlclient on Lambda
Launch Lambda on Boto3
Tweet from AWS Lambda
Run BigQuery from Lambda
Example of using lambda
Try AWS Lambda Destinations