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?
Top comments (4)
Lambda expressions are great in spots. The most common use is when you need a short function to pass as an argument to another function. However, list comprehensions remove the need for a lambda in a call to map. In the first example
could be replaced with
You probably want to avoid lambda when the function is long (like in your toGrade example), when the function is likely to be used elsewhere in your code or if creating a named function helps with documenting your intentions. Using your first example, defining the function
isEven
, orisLower
in the second would tilt the scales against using lambda.good point, the odds example is definitely overkill when a list comprehension is a possible solution. I think this also answers, the question of using lambda's for multi conditional solutions.
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?
thankyou