Python List comprehension is used to create a new list based on the condition from the given list. How do you create a python list comprehension of lambdas?
You can do this using functools.partial
.
Example lambda list comprehension in Python
Simple example code.
from functools import partial
# Your Code
def func_a(message: str) -> None:
print('a: ' + message)
def func_b(message: str) -> None:
print('b: ' + message)
msg = 'some message'
funcs = [func_a, func_b]
funcs_w_args = [partial(func, msg) for func in funcs]
# Now call partially defined functions
for func in funcs_w_args:
func()
Output:
Source: stackoverflow.com
Another example
res = [(lambda x: x * x)(x) for x in range(10)]
print(res)
Or better one
[x*x for x in range(10)]
Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Do comment if you have any doubts or suggestions on this lambda tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.