Try to guess the output (for more advanced learners)
From the Data Science Feed in the app comes this interesting part of code. Since peeps have asked in the app why it exactly behaves the way it does, I will try to give an explanation here as an answer. But first the code:
def multiplexers ():
return [lambda n: index * n for index in range(4)]
print([m (2) for m in multiplexers()])
You can find the (unexpected) output here:
And here comes my explanation:
The first thing to know is that the lambda in line 2 does not encompass the generator expression "for index in range(4). Envision it with parenthesis like this:
(lambda n: index * n) for index in range(4)
As you can now see, the lambda is defined (not called) 4 times (for indexes 0,1,2,3). The expression is inside a list comp. Because of that the function mulitplexers returns a list of 4 function objects (created by the lambda expression).
In line 3 we have another list comp where mulitplexers is called only once and each of the four function objects returned by multiplexers is called with 2 as an argument.
Now comes the big question! Why (as you can see from the output) is index == 3 in all function objects. The reason for that is the list comp in line 2. It defines the index variable which is referred to from all four function objects. The index variable is equal to 3 when the list comp stops and this is the value of index used by the function objects when called.
I assumed as much but that doesn‘t make any sense as there is even a badge for answering your own question.
Additionally the feed only seems to be available for the app but writing this kind of explanation on your phone kind of sucks.
Thoq! He is saying you
should post this in your feed, with "Share your thoughts" or similar, as this isn't question(or even if it is you know the answer) so not in compliance with SoloLearn Q&A guidelines. 😃
Hope you understand. Anyways this will probably be MFDed by gold/platinum mod.