How to invoke a function with return statement in list comprehension? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to invoke a function with return statement in list comprehension? (/thread-34307.html) |
How to invoke a function with return statement in list comprehension? - maiya - Jul-17-2021 Hi All, I want to invoke a function with return statement using list comprehension or even lambda (if possible) for the better performance. Below is code snippet where I am trying to achieve that in list comprehension where if that function return Fail then break the flow and control move to next statement. def func(var): return True if var % 2 else False l = [2, 2, 3, 4] new_list = [out for var in l out = func(var) if out == False break] print(new_list) But then I could not able to achieve the desired result, I would really appreciate if any suggestion on this. Similarly how to assign a value using list comprehension? Regards, Maiya RE: How to invoke a function with return statement in list comprehension? - Yoriz - Jul-17-2021 from itertools import takewhile def func(number): return True if number % 2 else False numbers = [2, 2, 3, 4] new_list = [number for number in numbers if not func(number)] print(new_list) new_list2 = list(takewhile(lambda number: not func(number), numbers)) print(new_list2)
RE: How to invoke a function with return statement in list comprehension? - maiya - Jul-17-2021 I want to store the return value from the function not the list numbers. RE: How to invoke a function with return statement in list comprehension? - Yoriz - Jul-17-2021 from itertools import takewhile def func(number): return True if number % 2 else False numbers = [2, 2, 3, 4] new_list = [func(number) for number in numbers if not func(number)] print(new_list) new_list2 = [func(number) for number in takewhile( lambda number: not func(number), numbers)] print(new_list2)
RE: How to invoke a function with return statement in list comprehension? - maiya - Jul-17-2021 (Jul-17-2021, 12:01 PM)Yoriz Wrote:Could you please explain the code sir? and here is that really required to call func method twice?from itertools import takewhile def func(number): return True if number % 2 else False numbers = [2, 2, 3, 4] new_list = [func(number) for number in numbers if not func(number)] print(new_list) new_list2 = [func(number) for number in takewhile( lambda number: not func(number), numbers)] print(new_list2) Regards, Maiya |