Intro to Maps, Filters and List Comprehension in Python
Learn how to use great python operations to speed up your coding!
How to use Maps, Filters and List Comprehension in Python.
This notebook will covers the tutorial of map,filter and list comprehension. It's me learning these python goodies and documenting aside, so someday I could look up and revise stuffs.
I am going through the course on Coursera called Python-3 Programming from University of Michigan. Gotta admit I learnt alot of Python from there and still doing. Earlier I used to take notes on Notion, but now I thought of getting my hands dirty by coding along and take notes in Colab.
Also anyone interested or wanna refresh their Python skills could even make use of it.
Maps
Python provides built-in functions map
and filter
, even a new syntax called list comprehension that lets you express a mapping/filtering operation. Most documentations and programmers use list comprehension and it seem's more like a pythonic way of writing code.
Map, and filter are commands that you would use in high-performance computing on big datasets. http://en.wikipedia.org/wiki/MapReduce
def doubleStuff(a_list):
'''
Returns a new list in which contains doubles of the elements in a list
'''
# Accum list
new_list = []
# Looping through values and making the calculation
for value in a_list:
double_elem = 2 * value
new_list.append(double_elem)
return new_list
# Using the above function
a_list = [1 , 2, 3 , 4, 5 , 6]
print(f'List before the values were got double: {a_list}')
double_list = doubleStuff(a_list)
print(f'\nThe list after the values they got double the number: {double_list}')
We can write the above function with less than one line of code using the map
function.
Map is a function which takes functions as the first input and sequence as an second input. map(function , sequence)
. Map just says apply the transforms (function) to every element in this sequence.
Map always expects a transformer function.
def double(value):
return 2*value
map_double_list = list(map(double , a_list))
print(f'Using map function: {map_double_list}')
I earlier tried just map(double , a_list)
which gave me just the map object. It turns out to be enclosing the map object by a list will gives us the list object.
But why this happens?
Map function returns an iterator, it doesn't want to store the list in it's memory. It's still an iterator and we can grab the list we needed by enclosing the map object by a list
which prevents pain to memory .
# Multiply 5 to every value
map_lambda_list = list(map(lambda value: 5*value , a_list))
print(f'Multiplying 5 to every element: {map_lambda_list}')
Let's Solve some Problems!
Gotta go through more: https://www.w3resource.com/python-exercises/map/index.php
- Below we have provided a list of strings called
abbrevs
. Use map to produce a new list calledabbrevs_upper
that contains all the same strings in upper case.
abbrevs = ['usa' , 'esp' , 'chn' , 'jpn' , 'mex' , 'can' , 'rus' , 'rsa' , 'jam']
upperAbbrev_list = []
for abbrev in abbrevs:
upperAbbrev_list.append(abbrev.upper())
print(upperAbbrev_list)
upperCase_abbrevs = list(map(lambda abbrev: abbrev.upper() , abbrevs))
print(upperCase_abbrevs)
- Using
map
, create a list assigned to the variablegreeting_doubled
that doubles each element in the list.
lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4]
lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4]
greeting_doubled = list(map(lambda element: 2 * element , lst))
print(greeting_doubled)
- Write a Python program to add three given lists using Python map and lambda
list(map(lambda a,b,c: a + b + c , [1 , 2 ,3] , [4 ,5 , 6] , [7 ,8 , 9]))
Filters
Filter function filter
takes two arguments same like our map
which has both function and a sequence parameters. Instead mapping them or making calculation with eachother, filter
filters out the numbers either True or False.
The function takes one item and return True if the item should. It is automatically called for each item in the sequence
filter
returns an iterator object like map, so we gotta wrap them by list
.
def keep_evens(a_list):
new_list = []
for elem in a_list:
if elem % 2 == 0:
new_list.append(elem)
return new_list
# Using the above function
mixList = [2 , 88 , 33 , 22 , 14 , 0 , 8 , 10 , 20 , 4]
evenList = keep_evens(mixList)
print(evenList)
filterEvenList = list(filter(lambda elem: elem % 2 == 0 , mixList))
print(filterEvenList)
- Using filter, filter
lst
so that it only contains words containing the letter 'o'. Assign to variablelst2
.
lst = ['witch' , 'halloween' , 'pumpkin' , 'cat' , 'candy' , 'wagon' ,'moon']
lst = ['witch' , 'halloween' , 'pumpkin' , 'cat' , 'candy' , 'wagon' , 'moon']
lst2 = list(filter(lambda elem: 'o' in elem , lst))
print(lst2)
- Write code to assign to the variable
filter_testing
all the elements inlst_check
that have a 'w' in them using filter.
lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya']
lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya']
filter_testing = list(filter(lambda word: 'w' in word , lst_check))
print(filter_testing)
List Comprehensions
Before we saw those two functions namely map
and filter
turns out to be we don't want to use them much (or) in other words we can use list comprehensions inplace of using map
and filter
. Better we can pull off more flexibility by using list comprehensions.
In simple words list comprehensions is a convinient syntax to do map
and filter
operations.
Basic Syntax of list comprehension:
[ <transformer_expression> for <iterator_variable> in <sequence> if <filteration_expression>]
def double(value):
return 2*value
map_double_list = list(map(double , a_list))
print(f'Using map function: {map_double_list}')
a_list
compre_double_list = [value * 2 for value in a_list]
compre_double_list
Breaking down by the syntax:
- transformer_expression :
value * 2
- iterator_varaible :
value
- sequence :
a_list
filterEvenList = list(filter(lambda elem: elem % 2 == 0 , mixList))
print(filterEvenList)
mixList
filterListComprehension = [element for element in mixList if element % 2 == 0]
filterListComprehension
filterListComprehension == filterEvenList
Write code to assign to the variable compri
all the values of the key name
in any of the sub-dictionaries in the dictionary tester
. Do this using a list comprehension.
tester = {'info': [{"name": "Lauren", 'class standing': 'Junior', 'major': "Information Science"},{'name': 'Ayo', 'class standing': "Bachelor's", 'major': 'Information Science'}, {'name': 'Kathryn', 'class standing': 'Senior', 'major': 'Sociology'}, {'name': 'Nick', 'class standing': 'Junior', 'major': 'Computer Science'}, {'name': 'Gladys', 'class standing': 'Sophomore', 'major': 'History'}, {'name': 'Adam', 'major': 'Violin Performance', 'class standing': 'Senior'}]}
inner_list = tester['info']
#print(inner_list)
# For Readability
import json
print(json.dumps(inner_list , indent = 2))
nameList = []
if True:
for dict_name in inner_list:
name = dict_name['name']
nameList.append(name)
print(nameList)
compri = [dict_value['name'] for dict_value in inner_list if True]
compri