8.9. Function Lambda

8.9.1. Rationale

  • Lambda - Anonymous functions

  • When function is used once

  • When function is short

8.9.2. Syntax

lambda <arguments>: <expression>

8.9.3. Definition

lambda x: x**2
lambda x: x%2==0
lambda x,y: x+y

8.9.4. Convention

  • Usually parameters are named x and y

  • Use shortest code possible

  • Do not assign lambda to variable

  • Usually there are no spaces in lambda expressions (to make code shorter)

lambda x,y: x+y
Listing 8.51. Lambda is anonymous function and it should stay anonymous. Do not name it.
squre = lambda x: x**2
squre(4)
# 16

8.9.5. Use Case

DATA = [1, 2, 3, 4]

def is_even(x):
    if x % 2 == 0:
        return True
    else:
        return False

list(filter(is_even, DATA))
# [2, 4]
DATA = [1, 2, 3, 4]

def is_even(x):
    return x % 2 == 0

list(filter(is_even, DATA))
# [2, 4]
DATA = [1, 2, 3, 4]

list(filter(lambda x: x%2==0, DATA))
# [2, 4]

8.9.6. Examples

Listing 8.52. Example 1
data = [1, 2, 3, 4]

def increment(x):
    return x + 1


list(map(increment, data))
# [2, 3, 4, 5]

list(map(lambda x: x+1, data))
# [2, 3, 4, 5]
Listing 8.53. Example 2
people = [
    {'age': 21, 'name': 'Jan Twardowski'},
    {'age': 25, 'name': 'Mark Watney'},
    {'age': 18, 'name': 'Melissa Lewis'}]

def adult(person):
    if person['age'] >= 21:
        return True
    else:
        return False


list(filter(lambda x: x['age'] >= 21, people))
# [{'age': 21, 'name': 'Jan Twardowski'},
#  {'age': 25, 'name': 'Mark Watney'}]
Listing 8.54. filter() example
people = [
    {'is_astronaut': False, 'name': 'Jan Twardowski'},
    {'is_astronaut': True, 'name': 'Mark Watney'},
    {'is_astronaut': True, 'name': 'Melissa Lewis'}]

def astronaut(person):
    return person['is_astronaut']

list(filter(lambda x: x['is_astronaut'], people))
# [{'is_astronaut': True, 'name': 'Mark Watney'},
#  {'is_astronaut': True, 'name': 'Melissa Lewis'}]

8.9.7. Assignments

8.9.7.1. Function Lambda Chain

English
  1. Use generator expression to create numbers: List[int]

  2. In generator use range() to get numbers from 1 to 33 (inclusive) divisible by 3

  3. Use filter() to get odd numbers from numbers

  4. Use map() to cube all numbers in numbers

  5. Use only lambda function in map() and filter()

  6. Create result: float with arithmetic mean of numbers

  7. Compare result with "Output" section (see below)

Polish
  1. Użyj wyrażenia generatorowego do stworzenia numbers: List[int]

  2. W generatorze użyj range() aby otrzymać liczby od 1 do 33 (włącznie) podzielne przez 3

  3. Użyj filter() aby otrzymać liczby nieparzyste z numbers

  4. Użyj map() aby podnieść wszystkie liczby w numbers do sześcianu

  5. Użyj tylko funkcji lambda w map() i filter()

  6. Stwórz result: float ze średnią arytmetyczną z numbers

  7. Porównaj wyniki z sekcją "Output" (patrz poniżej)

Output
result: float
# 11502.0
Hint
  • mean = sum(...) / len(...)

  • type cast to list() before calculating mean to expand generator