Table of contents Explained in a nutshell Reference Document/video: map(): applies transforamtion to each element filter(): keeps only valid data after filtering lambda function on filter zip(): combining iterables Explained in a nutshell map(func, iterable) — transform each elementInput: a function and an iterable (list, tuple, etc.)Logic: applies func to every element, one by oneOutput: a map object (wrap with list() to see results)Think of it as: “do this to every item”filter(func, iterable) — keep only matching elementsInput: a function that returns True/False + an iterableLogic: keeps only elements where func(element) returns TrueOutput: a filter object (wrap with list() to see results), holding original elements that passed the filterThink of it as: “only keep items that pass this test”zip(iter1, iter2, ...) — pair up elements across iterablesInput: two or more iterables of any typeLogic: pairs the nth element of each iterable into a tuple; stops at the shortest iterableOutput: a zip object of tuples (wrap with list() to see results)Think of it as: “stitch these lists together side by side” Reference Document/video: map(): applies transforamtion to each element def square ( x ):
return x ** 2
numbers = [ 1 , 2 , 3 , 4 , 5 ]
squared_numbers = list ( map ( square , numbers ))
filter(): keeps only valid data after filtering def is_even ( x ):
return x % 2 == 0
numbers = [ 1 , 2 , 3 , 4 , 5 ]
'''
Think of : filter(is_even,numbers) --> temp " [False, True, False, True, False] " --> [2,4]
IMPORANT: The filter object DOES NOT HOLD the booleans, but holds the original elemnts that passed the filter
'''
even_numbers = list ( filter ( is_even , numbers ))
lambda function on filter zip(): combining iterables names = [ ' Alice ' , ' Bob ' , ' Charlie ' ]
ages = [ 25 , 30 , 35 ]
combined = list ( zip ( names , ages ))
Another example with header list + elements nested list: headers = [ ' Name ' , ' Age ' , ' City ' ]
data = [[ ' Alice ' , 25 , ' New York ' ], [ ' Bob ' , 30 , ' Los Angeles ' ], [ ' Charlie ' , 35 , ' Chicago ' ]]
combined = list ( zip ( headers , * data ))
'''
Quick reminder of *data
* is the unpack operator
* unpacks exactly one layer:
'''
data = [[ ' Alice ' , 25 , ' New York ' ], [ ' Bob ' , 30 , ' Los Angeles ' ], [ ' Charlie ' , 35 , ' Chicago ' ]]
* data = [ ' Alice ' , 25 , ' New York ' ], [ ' Bob ' , 30 , ' Los Angeles ' ], [ ' Charlie ' , 35 , ' Chicago ' ]
Output would be: [( 'Name' , 'Alice' , 'Bob' , 'Charlie' ) , ( 'Age' , 25, 30, 35) , ( 'City' , 'New York' , 'Los Angeles' , 'Chicago' )]