Python: Lambda,Map,Filter,Reduce and Zip function

1. Lambda:
Syntax: lambda arguments : expressionA lambda function can take any number of arguments, but they can return only one value in the form of expression.
Single one line function ,Anoymous function(no name),no def, no return
Example 1: Find sum of Three numbers
add=lambda a,b,c: print(a+b+c)
add(4, 5, 1)Output- 10
Example 2: Find Biggest element(Nested If else in lambda)
find_max=lambda a,b,c:a if a>b and a>c
else (b if b>a and b>c else c)
print(find_max(6,15,1))Output- 15
2. Map:

Syntax: map(fun, iter)fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.
You can pass one or more iterable to the map() function.
The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) .
Example 1: Find squre of all elements in list
nums = [1, 2, 3, 4, 5] def sq(n):
return n*n square = list(map(sq, nums))print(square)Output: [1, 4, 9, 16, 25]
Example 2: Using Lambda inside map
nums = [1, 2, 3, 4, 5]square = list(map(lambda x: x**x, nums))print(square)Output: [1, 4, 9, 16, 25]
Example 3: Convert all elements of list in uppercase
people = ["lokesh", "bob", "tom", "developer"]up = list(map(lambda x: x.upper(), people))print(up)Output: ['LOKESH', 'BOB', 'TOM', 'DEVELOPER']
Example 4:
names = [
{'first': 'lokesh', 'last': 'sharma'},
{'first': 'Astha', 'last': 'verma'},
{'first': 'jiu', 'last': 'rai'}
]first_names = list(map(lambda x: x['first'], names))print(first_names)Output: ['lokesh', 'Astha', 'jiu']
3. Filter:

Syntax: filter(fun, Iter)fun: function that tests if each element of a sequence true or not.
Iter: Iterable which needs to be filtered.
Example 1: Filter out even and odd numbers from list
seq = [0, 1, 2, 3, 4, 5]
# result contains odd numbers of the list
result = filter(lambda x: x % 2, seq)
print(list(result))
# result contains even numbers of the list
result = filter(lambda x: x % 2 == 0, seq)
print(list(result))Output:
[1, 3, 5]
[0, 2, 4]
For Example 2,3: A dictionary Users(twitter database) is given in which we have username and tweets.
users = [
{"username": 'samuel', "tweets": ["i love cake", "i am good"]},
{"username": 'andy', "tweets": []},
{"username": 'kumal', "tweets": ["India", "Python"]},
{"username": 'sam', "tweets": []},
{"username": 'lokesh', "tweets": ["i am good"]},
]Example 2:Filter out Users which dont have any tweets/Inactive Users
inactive_users = list(filter(lambda a:not a['tweets'], users))print(inactive_users)Output: [{'username': 'andy', 'tweets': []},
{'username': 'sam', 'tweets': []}
]
Example 3: Filter inactive users with just username in uppercase.
inactive_users=list(map(lambda x:x["username"].upper(),
filter(lambda a:not a['tweets'], users)))print(inactive_users)Output:['ANDY', 'SAM']
Example 4: Return a new list with the string “your name is” + name ,but only if length of name is bigger than 4
names=['lokesh','lassie','bob','to']new=list(map(lambda name:f"your name is {name}",
filter(lambda x:len(x)>4,names)))print(new)Output:['your name is lokesh', 'your name is lassie']
4.Reduce:

The reduce() function accepts a function and a sequence and returns a single value calculated as follows:
- Initially, the function is called with the first two items from the sequence and the result is returned.
- The function is then called again with the result obtained in step 1 and the next value in the sequence. This process keeps repeating until there are items in the sequence.
Example-1 Find Multiply of all elements in list
from functools import reduce
seq=[2,3,4,5,6]multiply=reduce(lambda a,b:a*b,seq)print(multiply)Output:720First: It takes 2,3 and return 6
Second: It takes 6 and 4, retuen 24
Third: It takes 24 and 5, return 220
Fourth: It takes 220 and 6, return 720
All elements in sequence are over so it returns 720 as output.
5. Zip:
The zip() function take iterables (can be zero or more), makes iterator that aggregates elements based on the iterables passed, and returns an iterator of tuples.
Syantax: zip(*iterables)Return Value from zip()
The zip() function returns an iterator of tuples based on the iterable object.
- If no parameters are passed, zip() returns an empty iterator
- If a single iterable is passed, zip() returns an iterator of 1-tuples. Meaning, the number of elements in each tuple is 1.
- If multiple iterables are passed, ith tuple contains ith Suppose, two iterables are passed; one iterable containing 3 and other containing 5 elements. Then, the returned iterator has 3 tuples. It’s because iterator stops when shortest iterable is exhaused.
Example 1:Create list of tuples with combined name,roll_no and marks
name = ["Manjeet", "Nikhil", "Shambhavi"]
roll_no = [4, 1, 3]
marks = [40, 50, 60]
mapped = zip(name, roll_no, marks)
print(list(mapped))Output:
[('Manjeet', 4, 40), ('Nikhil', 1, 50), ('Shambhavi', 3, 60)]
Example 2: Create dictionary from Two iterables:
name = ["Manjeet", "Nikhil", "Shambhavi"]
marks = [40, 50, 60]
mapped = zip(name, marks)
print(dict(mapped))Output:
{'Manjeet': 40, 'Nikhil': 50, 'Shambhavi': 60}
