### Lambda function¶

- a simple one line function
- no def or return keywords

##### Example¶

Let's write a python funtion to find maximum of two numbers.##### 1) Normal way:¶

In [28]:

```
def max_between(x,y):
if x>y:
return x
else:
return y
print(max_between(10,80))
```

##### 2) Lambda funtion to find maximum of two numbers¶

In [29]:

```
max_bet_lambda = lambda x,y:x if x>y else y
```

In [30]:

```
print(max_bet_lambda(10,80))
```

### Map function¶

- Map function are used to apply a same funtion to each element in a sequence.
- Returns a modified sequence

In [31]:

```
def mul_2(x):
return 2*x
num_list = [1,2,3,4,5]
a = map(mul_2,num_list)
print(a)
print(list(a))
```

In [32]:

```
num_list = [1,2,3,4,5]
print(list(map(lambda x: 2*x,num_list)))
```

###### Note : In list comprehension way:¶

In [33]:

```
print([2 * x for x in num_list])
```

### Filter funtion¶

- This function filters element in a sequence based on a given condition.
- It returns a filtered list.

##### Finding even numbers in a list using filter function.¶

In [34]:

```
num_list = [1,2,3,4,5,6,7,8,9,10]
print(list(filter(lambda x: x%2==0,num_list)))
```

##### Note : In a list comprehension way:¶

In [35]:

```
print(list(x for x in num_list if x %2==0))
```

### Reduce function¶

- This function apply a same operation to all the elements in a sequence.
- It uses result of first operation as a first param to the next operation.
- It returns a single value, and not a list
- To use reduce function, import reduce from functools package.

##### Multiply all the values in a list¶

In [38]:

```
from functools import reduce
num_list = [1,2,3,4,5]
print(reduce(lambda x,y : x*y,num_list))
```

## No comments :

## Post a Comment