I am a beginner in python and currently I am learning how lambda functions work. I want to know if there is a way for me to influence the output of a lambda + filter combo, because if I have understood how they work correctly, you can only return the element of the list you are iterating over, i.e., the argument of the lambda function. What I am exactly trying to achieve can be shown using a list comprehension
numbers = [25, 91, 22, -7, -20]
numbers_div_5_str = [str(n) for n in numbers if n % 5 == 0]
This gives a list of numbers in the form of a string that are divisible by 5. I want to achieve the same using lambda + filter, if possible
This is what I tried doing
numbers = [25, 91, 22, -7, -20]
numbers_div_5 = list(filter(lambda a : a % 5 == 0, numbers))
output -> [25, -20]
Expected output -> ['25', '-20']
In your example with a list comprehension you are doing two kinds of operations. 1) filtering elements from the original list with if n % 5 == 0
and 2) casting the values to be of type str
with str(n)
.
Using the filter
function can help you achieve your filtering (1) in exactly the way you tried already. The only thing remaining is to cast the values to str
. Unfortunately you cannot just say str([1,2,3])
to transform all numbers in that list to be of type str
. This has to be done element-wise. To achieve this you can use map
. The syntax is roughly the same as filter
, but this will take each element from your list and apply some kind of logic to it. This logic can be specified in a lambda
function, or in this case you can simply use str
on its own to cast your values.
here is an example in code
numbers = [25, 91, 22, -7, -20]
filtered_numbers = filter(lambda a : a % 5 == 0, numbers)
filtered_str_numbers = list(map(str, filtered_numbers))
Or more concise:
filtered_str_numbers = list(map(str, filter(lambda a : a % 5 == 0, numbers)))
Of course it's good to explore these functions and how they work for your knowledge, but in my experience it's totally fine to stick to list comprehensions in most cases.