12 AnswersNew Answer
Oma Falk here is a better explanation, after reading more about generators. In list comprehensions, all evaluations are done before actually returning the list. Which means you must wait for the evaluations to finish before you access it. None of the functions are returned, and they are only assigned after all evaluations are done, thus all of them having the same last operator. A generator on the other hand allows you to access each element independetly. Which means that at first, it doesn't evaluate anything at all. So when it runs the first time, it returns the first value of "op", which was "+", and return it as a function. After that, it revaluates the output, and this time even when the variable "op" changes, it will not affect the first "add" function because it has already been defined and finished. Same goes for the two remaining functions. (I'm not sure if you understood, I can think of a better way to explain this if you wish to. This can be quite confusing at first).)
This is a common problem with lambda and loops. When you define lambda function inside a loop, any variable that changes inside the loop will be modified, and will also modify the lambda function itself. To avoid this, you can pass the variables that change within the loop as arguments of the function: https://code.sololearn.com/cKZTZw8M5td9/?ref=app
Aymane Boukrouh I hoped using tuples do it. Whats the difference to https://code.sololearn.com/cNU52yK69BSj/?ref=app
Aymane Boukrouh but doesnt that makes the operator accessible from parameter ? like add(2,3,"+4*") would change the function entirely. i can only came up with this, but its not one liner https://code.sololearn.com/cZqfscD4x2fU/?ref=app
Oma Falk It's a generator. To create tuple comprehension you can use: tuple([...]) But this creates a generator: (...)
I found this https://stackoverflow.com/questions/6076270/lambda-function-in-list-comprehensions/6076304 Based on it I wrote another version of "function comprehension" with partial() https://code.sololearn.com/cqug6Ml0O7dI/?ref=app
You somehow created a shared local variable for the functions, but where is it stored? Very annoying problem.
Oma Falk This is not a tuple: (i for i in range(10))
Seb TheS but omas is a tuple edit:nope 🤔
Oma Falk interesting, I didn't know you can do it like this as well. First of all, as Seb TheS mentioned, this is a generator not a tuple. Anyway, here is my interpretation: A generator saves the results in memory, without actually doing the calculations. In this case, I would say that for each loop it saves the lambda function as a new one, until being called.
Taste yes, it does make it accessible from outside the function. However, in python 3.8, I believe there is a new syntax that prevents the user from accessing certain default values of parameters. Not sure tho.
Aymane Boukrouh I got it a bit. It is midnight. have to sleep about it