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]

14th Apr 2023, 3:19 PM
Somvir Dhaka
Somvir Dhaka - avatar
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
14th Apr 2023, 3:40 PM
Darpan kesharwani🇮🇳[Inactive📚]
Darpan kesharwani🇮🇳[Inactive📚] - avatar
+ 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
14th Apr 2023, 3:44 PM
Tibor Santa
Tibor Santa - avatar
+ 1
Thanks
15th Apr 2023, 7:21 AM
Somvir Dhaka
Somvir Dhaka - avatar