![]() |
Issues with Lambda Function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Issues with Lambda Function (/thread-10473.html) |
Issues with Lambda Function - fad3r - May-22-2018 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. RE: Issues with Lambda Function - buran - May-22-2018 you need list comprehension in the lambda RE: Issues with Lambda Function - ThiefOfTime - May-22-2018 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 :) RE: Issues with Lambda Function - fad3r - May-22-2018 (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)) RE: Issues with Lambda Function - buran - May-22-2018 @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] RE: Issues with Lambda Function - fad3r - May-22-2018 (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. 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. |