lambda functions within list comprehensions

Jean-Paul Calderone exarkun at divmod.com
Sat Oct 29 17:47:44 EDT 2005


On 29 Oct 2005 14:25:24 -0700, Max Rybinsky <sunspire at gmail.com> wrote:
>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
>[<function <lambda> at 0x010F3DF0>, <function <lambda> at 0x010F7CF0>,
><function <lambda> at 0x010F7730>, <function <lambda> at 0x010FD270>,
><function <lambda> at 0x010FD0B0>, <function <lambda> at 0x010FD5B0>,
><function <lambda> at 0x010FD570>, <function <lambda> at 0x010FD630>,
><function <lambda> at 0x01100270>, <function <lambda> at 0x011002B0>]
>
>...and functions are likely to be different.

A search of this group would reveal one or two instances in the past in which this question has been asked and answered:

  http://article.gmane.org/gmane.comp.python.general/427200
  http://article.gmane.org/gmane.comp.python.general/424389
  http://article.gmane.org/gmane.comp.python.general/399224
  http://article.gmane.org/gmane.comp.python.general/390097
  http://article.gmane.org/gmane.comp.python.general/389011
  http://article.gmane.org/gmane.comp.python.general/334625

I could go on for a while longer, but hopefully some of the linked material will answer your question.

Jean-Paul



More information about the Python-list mailing list