Lambda, Map, Reduce, Filter, and other Special Function Flashcards
(22 cards)
____ Functions are anonymous functions means that the function is without a name.
lambda
s1 = ‘GeeksforGeeks’
s2 = lambda func: func.upper()
print(s2(s1))
GEEKSFORGEEKS
Python lambda function syntax
Syntax: lambda arguments : expression
Example: Check if a number is positive, negative, or zero
n = lambda x: “Positive” if x > 0 else “Negative” if x < 0 else “Zero”
print(n(5))
print(n(-3))
print(n(0))
Positive
Negative
Zero
Lambda with List Comprehension
li = [lambda arg=x: arg * 10 for x in range(1, 5)]
for i in li:
print(i())
10
20
30
40
Example: Check if a number is even or odd
check = lambda x: “Even” if x % 2 == 0 else “Odd”
print(check(4))
print(check(7))
Even
Odd
Lambda Function with Multiple Statements
Example: Perform addition and multiplication in a single line
calc = lambda x, y: (x + y, x * y)
res = calc(3, 4)
print(res)
The _____ function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a ____ object (which is an iterator).
map
s = [‘1’, ‘2’, ‘3’, ‘4’]
res = map(int, s)
print(list(res))
[1, 2, 3, 4]
Syntax for map function
map(function, iterable)
a = [1, 2, 3, 4]
Using custom function in “function” parameter
# This function is simply doubles the provided number
def double(val):
return val*2
res = list(map(double, a))
print(res)
[2, 4, 6, 8]
a = [1, 2, 3, 4]
Using lambda function in “function” parameter
# to double each number in the list
res = list(map(lambda x: x * 2, a))
print(res)
[2, 4, 6, 8]
Map with multiple iterables
a = [1, 2, 3]
b = [4, 5, 6]
res = map(lambda x, y: x + y, a, b)
print(list(res))
[5, 7, 9]
words = [‘apple’, ‘banana’, ‘cherry’]
res = map(lambda s: s[0], words)
print(list(res))
[‘a’, ‘b’, ‘c’]
s = [’ hello ‘, ‘ world ‘, ‘ python ‘]
res = map(str.strip, s)
print(list(res))
[‘hello’, ‘world’, ‘python’]
The ______ method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.
filter
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.
[2, 4, 6]
syntax for filter() function
Syntax: filter(function, sequence)
function: A for filter
function that defines the condition to filter the elements. This function should return True for items you want to keep and False for those you want to exclude.
iterable for filter
The iterable you want to filter (e.g., list, tuple, set
a = [1, 2, 3, 4, 5, 6]
b = filter(lambda x: x % 2 == 0, a)
print(list(b))
[2, 4, 6]
Combining filter and map
a = [1, 2, 3, 4, 5, 6]
First, filter even numbers
b = filter(lambda x: x % 2 == 0, a)
Then, double the filtered numbers
c = map(lambda x: x * 2, b)
print(list(c))
[4, 8, 12]