lambda in list comprehension acting funny

rusi rustompmody at gmail.com
Fri Jul 13 10:45:29 EDT 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)
1
>>> fs[1](2)
2
>>> fs[2](2)
4
>>> fs= assign_version([0,1,2])
>>> fs[0](2)
4
>>> fs[1](2)
4
>>> fs[2](2)
4


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /