Files

104 lines
2.0 KiB
Plaintext

-> Common function used in python:
map, filter, zip, and replace
-> map:
Prototype:
map(<function>, <iterable>)
Whatever the first argument, i.e., function can do, map will do
the same logic for each item in the iterable and return the
iterable with same structure.
for ex:
my_list = [1,2,3]
def multiply_by2(item):
return item*2
print(list(map(multiply_by2, my_list)))
print(my_list)
-> filter:
Prototype:
filter(<function>, <iterable>)
To filter some items from the iterable based on the condition
defined in the function which return some boolean value.
for ex:
my_list = [1,2,3]
def only_odd(item):
return item % 2 == 0
print(list(filter(only_odd, my_list)))
print(my_list)
-> zip:
Prototype:
zip(<iterable1> , <iterable2>)
combine each items from both iterable together.
for ex:
my_list = [1, 2, 3]
your_list = [10, 20, 30]
print(list(zip(my_list, your_list)))
print(my_list)
Output:
[(1,10), (2,20), (3,30)]
-> reduce:
to use reduce add the below line:
from functools import reduce
# What reduce does?
# reduce take the function given and take item from the
# iterable and pass to function given to it. The first
# parameter is the value initialized as the 3rd argument
# to the reduce function. It do the processing and returns
# a value which is used as next initialiizing value for the
# first argument of the function provided in the reduce function
# and so on for all items in iterable.
-> lambda expressions:
one time anonymous function.
Prototype:
lambda item: <action on param>
for ex:
my_list = [1,2,3]
print(list(map(lambda item: item*2, my_list)))
-> list comprehension:
for ex:
my_list = [char for char in 'hello']
print(my_list)