Try to guess the output (for more advanced learners) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

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: https://code.sololearn.com/c5eB6z7w2PD1/#py

28th Apr 2019, 8:37 PM
Thoq!
Thoq! - avatar
5 Answers
+ 4
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.
28th Apr 2019, 8:38 PM
Thoq!
Thoq! - avatar
+ 3
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.
28th Apr 2019, 11:45 PM
Thoq!
Thoq! - avatar
+ 2
Jay Matthews What do you mean with my feed?
28th Apr 2019, 9:23 PM
Thoq!
Thoq! - avatar
+ 2
I can see that but what does it have to do with my post?
28th Apr 2019, 10:23 PM
Thoq!
Thoq! - avatar
+ 1
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.
28th Apr 2019, 11:40 PM
Emoji FanBoy
Emoji FanBoy - avatar