+ 2
Can anyone explain to me why the output in this code is [6,6,6,6]
First I would be happy if someone could explain to me the output of this line of code "return[lambda x:i*x for i in range(4)]" , then last one , bringing this output [6,6,6,6] . #Codes def multiplier(): return[lambda x:i*x for i in range(4)] print ([m(2) for m in multiplier()])
2 odpowiedzi
+ 6
Emmanuel Massawe ,
the function you are using is returning a lambda object. i am not sure what you want to achieve with this, or if it comes by accident.
if you just want to take a number from a range and multiply it by an other number, you could do:
def multiplier():
return [i*2 for i in range(4)]
print(multiplier()) # result is [0,2,4,6]
if you have a different intent, please give a description what you want to achieve.
thanks!
+ 2
multiplier() return an array (comprehension) wich contains 4 times the lambda x: i*x
so your code (I guess it comes from a challenge) is equivalent to:
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)