A quick understanding of using functional methods like map, filter, & sorted with and without lambda functions. A great example of how lambda functions work in python.
use the filter function to remove items from a list
without lambda
def filterFunc(x):
if x % 2 == 0:
return False
return True
nums = (1, 8, 4, 5, 12, 26, 381, 58, 47)
odds = list(filter(filterFunc, nums))
[1, 5, 381, 47]
with lambda
mylist = [1, 2, 3, 4, 5]
odds = list(filter((lambda x: x % 2 != 0), mylist))
[1, 5, 381, 47]
remove uppercase from string
without lambda
def filterFunc2(x):
if x == x.upper():
return False
return True
chars = "aBcDeFghoiJk"
lower = list(filter(filterFunc2, chars))
['a', 'c', 'e', 'g', 'h', 'o', 'i', 'k']
with lambda
lower = list(filter((lambda x: x == x.upper()), chars))
['a', 'c', 'e', 'g', 'h', 'o', 'i', 'k']
return new list with index squared
without lambda
def squareFunc(x):
return x ** 2
ints = [1, 2, 3, 4, 5]
squared = list(map(squareFunc, ints))
[1, 4, 9, 16, 25]
with lambda
squared = list(map(lambda x: x ** 2, ints))
[1, 4, 9, 16, 25]
use sorted and map to change numbers to grades
def toGrade(x):
if x >= 90:
return "A"
elif x >= 80:
return "B"
elif x >= 70:
return "C"
elif x >= 60:
return "D"
else:
return "F"
grades = (81, 89, 94, 78, 61, 99, 74, 90)
order = sorted(grades)
final = list(map(toGrade, order))
['D', 'C', 'C', 'B', 'B', 'A', 'A', 'A']
Challenge:
Is using a lambda function a good choice here? If so, how will you do it?
Thank you for a great quick write up!
I found a typo here.
...
use the filter function to remove items from a list
with lambda
...
Should be...
without lambda
right?