lambda functions within list comprehensions

2005-10-29 Thread Max Rybinsky
Hello!

Please take a look at the example.

>>> a = [(x, y) for x, y in map(None, range(10), range(10))] # Just a list of 
>>> tuples
>>> a
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8,
8), (9, 9)]

Now i want to get a list of functions x*y/n, for each (x, y) in a:

>>> funcs = [lambda n: x * y / n for x, y in a]

It looks consistent!

>>> funcs
[ at 0x010F3DF0>,  at 0x010F7CF0>,
 at 0x010F7730>,  at 0x010FD270>,
 at 0x010FD0B0>,  at 0x010FD5B0>,
 at 0x010FD570>,  at 0x010FD630>,
 at 0x01100270>,  at 0x011002B0>]

...and functions are likely to be different.

>>> funcs[0](1)
81

But they aren't!

>>> for func in funcs:
... print func(1)
...
81
81
81
81
81
81
81
81
81
81

It seems, all functions have x and y set to 9.
What's wrong with it? Is it a bug?

On the other hand, this problem has a solution:

>>> def buldFunc(x, y):
... return lambda n: x * y / n
...
>>> funcs = [buldFunc(x, y) for x, y in a]

... and it does work!

But why not to save several lines of code? ;)

Thanks in advance.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda functions within list comprehensions

2005-10-29 Thread Max Rybinsky
Thank you for explanation, Alex.
It appears that almost every beginner to Python gets in trouble with
this ...feature. :)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda functions within list comprehensions

2005-10-30 Thread Max Rybinsky
OK.
The thing i've got is an obscure semantic bug, occured because of my
unawareness of the following Python "features":
1. (In major)
http://mail.python.org/pipermail/python-dev/2005-September/056508.html
2. "late" bindings of the function's body

Got to know! :)

Thanks for your attention.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda functions within list comprehensions

2005-10-30 Thread Max Rybinsky
Valid link in my previews message is

http://mail.python.org/pipermail/python-dev/2005-September/056669.html

Sorry.

-- 
http://mail.python.org/mailman/listinfo/python-list