Map, Zip & Filter | Understanding Python built-in functions.
In Python, map()
, zip()
, and filter()
are built-in functions that are used to perform different operations on iterables like lists, tuples, and sets.
map()
function: This function applies a given function to each item of an iterable and returns a new iterable with the results.
Syntax: map(function, iterable)
Example:
# Convert Celsius to Fahrenheit
celsius = [39.2, 36.5, 37.3, 37.8]
fahrenheit = list(map(lambda x: (9/5)*x + 32, celsius))
print(fahrenheit)
Output:
[102.56, 97.7, 99.14, 100.03999999999999]
zip()
function: This function takes one or more iterables and aggregates them into a single iterable of tuples.
Syntax: zip(*iterables)
Example:
# Merge two lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
merged_list = list(zip(list1, list2))
print(merged_list)
Output:
[(1, 'a'), (2, 'b'), (3, 'c')]
filter()
function: This function applies a given function to each item of an iterable and returns a new iterable with the items for which the function returns True.
Syntax: filter(function, iterable)
Example:
# Find all even numbers in a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Output:
[2, 4, 6, 8, 10]
Summary
Here are some key takeaways about map()
, zip()
, and filter()
functions in Python:
map()
is a built-in function that applies a given function to each item of an iterable and returns a new iterable with the results.zip()
is a built-in function that aggregates one or more iterables into a single iterable of tuples.filter()
is a built-in function that applies a given function to each item of an iterable and returns a new iterable with the items for which the function returns True.These functions can be used to simplify code and make it more concise.
These functions can be used to perform common data manipulation tasks, such as converting units of measurement, merging data from multiple sources, and filtering data based on specific criteria.
These functions are often used in combination with lambda functions to perform simple operations on iterables.
Subscribe to my newsletter
Read articles from Nikhil Akki directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Nikhil Akki
Nikhil Akki
I am a Full Stack Solution Architect at Deloitte LLP. I help build production grade web applications on major public clouds - AWS, GCP and Azure.