On Dec 21, 11:37 pm, cjrh <caleb.hatti...@gmail.com> wrote:
> def g(i):
>     def f(x):
>         return x + i
>     return f
> my_list_of_functions = [g(i) for i in range(10)]

I suspect the following won't be of immediate use to you, but it is
worth hearing about right now, even if it'll only make sense sometime
later in the future.  This also works:

my_list_of_functions = [lambda x, j=i : x + j for i in range(10)]

However, you can see how the version using "def", above, is much
clearer than this new version using lambda.  You need really sharp
eyes to catch the scoping trick: the "j" belongs to the inner scope of
the lambda, while the "i" belongs to the outer scope of the list
comprehension.  The contents are copied from i to j at the time of
each lambda declaration, which is why it works.  In a large body of
code, these kinds of micro-tricks make it hard to read code.

Because Python's scoping rules are strict and clean, we can even do
the following:

my_list_of_functions = [lambda x, i=i : x + j for i in range(10)]

Now, again in a large body of code, this kind of thing can make it
very tricky to read code quickly.  You need especially sharp eyes to
spot that there are two "i"s here: one belongs to the inner scope of
the lambda function, and one belongs to the outer scope in the list
comprehension (and again, the contents of the outer "i" are copied
over to the inner "i" at the moment each lambda function is created).

This is why, except for the simple common cases, def is often better,
simply for the sake of readability.

Reply via email to