lambda
# Syntax: lambda arguments: expression
# EXAMPLE 1
add = lambda a, b, c: a + b + c
print(add(4, 5, 1)) # 10
# EXAMPLE 2
double = lambda x: x * 2
print(double(5)) # 10map()
map() returns map object (which is iterator), it is the result after applying the given function to each item in iterable (list, tuple)
filter() - filter (check by True, False)
# 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]
odd_seq = filter(lambda x: x % 2 == 1, seq)
even_seq = filter(lambda x: x % 2 == 0, seq)
print(list(odd_seq)) # [1, 3, 5]
print(list(even_seq)) # [0, 2, 4]# 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) # ['your name is lokesh', 'your name is lassie']reduce()
reduce() 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.
from functools import reduce
# EXAMPLE 1: Find Multiply of all elements in list
seq = [2,3,4,5,6]
multiply = reduce(lambda a, b: a * b, seq)
print(multiply)
"""
Output: 720
First: 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.
"""zip()
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.
- If no arg → zip() returns empty iterator
- If 1 arg → it returns each item bounded in tuple
- If 2 and more args → it returns aggregation till shortest one