0
def multi(): return [lambda x:i*x for i in range(4)] print ([m(2) for m in multi()])
Please explain working of this snippet how output is [6,6,6,6]
3 ответов
+ 3
Somvir Dhaka
multiplier() return an array (comprehension) wich contains 4 times the lambda x: i*x
so your code is..
mult = [
lambda x: i*x,
lambda x: i*x,
lambda x: i*x,
lambda x: i*x,
]
print([m(2) for m in mult])
the print print the array (comprehension) of each function returning last value of i (3) multplied by argument given (2)
You can see this For more..
https://stackoverflow.com/questions/56177380/the-output-of-lambda-xix-for-i-in-range4
+ 2
Recommended literature:
https://stackoverflow.com/questions/6076270/lambda-function-in-list-comprehensions
This one is a very nasty example and solving it requires a deep understanding of Python's internal evaluation order of its syntax: lambda vs list comprehension.
A cleaner solution that will reach the expected result, is utilizing functools.partial
+ 1
Thanks