Python Forum

Full Version: Issues with Lambda Function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I am trying to wrap my head around lambda but I am running into issues.

The homework question is: Write a lambda function that takes a list my_list and returns a list which includes only even numbers

my_list = [1, 5, 4, 6, 8, 11, 3, 12]
test = lambda my_list: my_list % 2 == 0


print test(my_list)
I feel like that should do it but I get an error when I try to run it. Not sure what is wrong with my logic.
you need list comprehension in the lambda
The Problem is that any numerical operand is only defined for values (int, double, long, etc.) not for lists.
the first solution that pops into my mind is:
my_list = [1,5,4,6,8,11,3,12]
test = lambda mylist: [el for el in mylist if el % 2 == 0]

print(test(my_list))
what you are doing is to get every element in the list, check if it is even and pack all even elements into a new list.
If the amount of elements becomes too high use numpy instead, there you can also use masks. But for small lists this would be a solution. but since you are constructing a new list you could use the list comprehension without the explizit function and lambda, but that depends on what you want to do with the lambda :)
(May-22-2018, 03:51 PM)buran Wrote: [ -> ]you need list comprehension in the lambda

The list comp does help but it returns boolean expression unless I did it wrong?

my_list = [1, 5, 4, 6, 8, 11, 3, 12]
test = lambda my_list: [my_list % 2 == 0 for my_list in my_list]


print (test(my_list))
@ThiefOfTime already post the right solution
My code is the same
test = lambda my_list: [x for x in my_list if not x%2]
(May-22-2018, 03:58 PM)ThiefOfTime Wrote: [ -> ]The Problem is that any numerical operand is only defined for values (int, double, long, etc.) not for lists.
the first solution that pops into my mind is:
my_list = [1,5,4,6,8,11,3,12]
test = lambda mylist: [el for el in mylist if el % 2 == 0]

print(test(my_list))
what you are doing is to get every element in the list, check if it is even and pack all even elements into a new list.
If the amount of elements becomes too high use numpy instead, there you can also use masks. But for small lists this would be a solution. but since you are constructing a new list you could use the list comprehension without the explizit function and lambda, but that depends on what you want to do with the lambda :)

Yup this totally solves it. I have to spend some time to understand why yours works your way and mine at the bottom creates a boolean. The tip on the numerical operand piece was super helpful. I totally didnt know that.