lambda in list comprehension acting funny

rusi rustompmody at
Fri Jul 13 16:45:29 CEST 2012

To come back to the OPs question.

Variables can be assigned. Or they can be bound.
[C++ programmers will be familiar with the difference between
initialization and assignment]

List comprehensions are defined in terms of assignment to the local
variable rather than binding.
Hence the issue.

Below are two functions that simulate mapping (lambda x: x**i) where
the i's come from some given list

def binding_version(lst):
    if not lst: return []
    i = lst[0]
    return [(lambda x: x ** i)] + binding_version(lst[1:])

def assign_version(lst):
    ret = []
    for i in lst:
        ret.append(lambda x: x**i)
    return ret

>>> fs= binding_version([0,1,2])
>>> fs[0](2)
>>> fs[1](2)
>>> fs[2](2)

>>> fs= assign_version([0,1,2])
>>> fs[0](2)
>>> fs[1](2)
>>> fs[2](2)

More information about the Python-list mailing list