Lambda

Lambda expressions are derived from lambda calculus. They are used in practice
as one-line, unnamed (anonymous) functions. They are especially relevant in
functional programming context but are universally applicable.

Simple one

#lambda
x1 = lambda x: x * 2
print(x1(4))

x2 = lambda x,y : x / y
print(x2(10,2))

x3 = lambda x,y,z : x*y/z
print(x3(4,2,10))

If statement, sorted

#lambda instead if statement:
CheckValue = lambda x , y : x if x > y else y
print(CheckValue(3,2))
print(CheckValue(-3,0))

#lambda as key
animals = [
( 'moose' , 'male' , 360 ),
( 'deer' , 'male' , 200 ),
( 'dave' , 'female' , 14 ),
]
animals_by_weight = 
sorted (animals, key = lambda animal : animal[ 2 ])
print (animals_by_weight)

In functions

#lambda in functions
def multiply(n):
  return lambda x : x * n

multi2 = multiply(2)
multi3 = multiply(3)

print(multi2(3))
print(multi3(3))

In classes

#lambda in classes
from operator import itemgetter, attrgetter

class Wilds:
    def __init__(self, name, sex, weight):
        self.name = name
        self.sex = sex
        self.weight = weight

    def _repr_(self):
        return repr((self.name, self.sex, self.weight))

anim_objs = [
Wilds( 'moose' , 'male' , 360 ),
Wilds( 'deer' , 'male' , 200 ),
Wilds( 'dave' , 'female' , 14 ),
]
print ( sorted (anim_objs, key = lambda x : x.weight ))
print ( sorted (anim_objs, key =attrgetter( 'weight' )))