Python Notes

# Using lambda expressions

Lambda expressions create anonymous functions. Although such functions do not have identifier names, a lambda expression can be assigned to a variable like any other Python object.

The body of the lambda functions is short and simple, consists of a single expression. The lambda function can be used on place or assigned to a variable. In the second case, it can be used repeatedly, calling as an usual function.

The usage on place. In the second parentheses, the arguments for the function are passed:

```>>> f = (lambda a, b: a + b) (10, 5)
>>> f
15```

Associating lambda function with variable:

```>>> f = lambda a, b: a + b
>>> f
<function <lambda> at 0x7fdd74831bf8>
>>> f(10, 5)
15
>>> f(-3, -1)
-4```

List of lambda expressions. The result is a list of actions performed on demand.

```a3 = [(lambda x,y: x+y),(lambda x,y: x-y),(lambda x,y: x*y),(lambda x,y: x/y)]
b = a3(5, 12)```

Dictionary containing lambda functions:

```a4 = {'pos':lambda x: x-1, 'neg':lambda x: abs(x)-1, 'zero':lambda x: x}
b = [-3, 10, 0, 1]
for i in b:
if i < 0:
print(a4['neg'](i))
elif i > 0:
print(a4['pos'](i))
else:
print(a4['zero'](i))```

Lambda functions are often used as arguments to the key parameter of the sort() method or to the sorted() function.

```>>> d = {'a': 10, 'b': 15, 'c': 4}
>>> list_d = list(d.items())
>>> list_d
[('a', 10), ('b', 15), ('c', 4)]
>>> list_d.sort(key=lambda i: i)
>>> list_d
[('c', 4), ('a', 10), ('b', 15)]```