## DEV Community is a community of 862,249 amazing developers

We're a place where coders share, stay up-to-date and grow their careers. dillan teagle

Posted on • Originally published at teaglebuilt.github.io

# with & without lambda in python

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

``````
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)

``````

['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?

## Discussion (4) David Nehme

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

``````odds = list(filter(filterFunc, nums))
``````

could be replaced with

``````[num for num in nums if num % 2]
``````

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`, or `isLower` in the second would tilt the scales against using lambda. dillan teagle

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.