KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I wanted to have a list of lambdas that act as sort of a cache to some heavy computation and noticed this: >>> [j() for j in [lambda:i for i in range(10)]] [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] Although >>> list([lambda:i for i in range(10)]) [<function <lambda> at 0xb6f9d1ec>, <function <lambda> at 0xb6f9d22c>, <function <lambda> at 0xb6f9d26c>, <function <lambda> at 0xb6f9d2ac>, <function <lambda> at 0xb6f9d2ec>, <function <lambda> at 0xb6f9d32c>, <function <lambda> at 0xb6f9d36c>, <function <lambda> at 0xb6f9d3ac>, <function <lambda> at 0xb6f9d3ec>, <function <lambda> at 0xb6f9d42c>] Meaning that the lambdas are unique functions but they somehow all share the same index value. Is this a bug or a feature? How do I avoid this problem? It's not limited to list comprehensions... >>> funcs = [] ... for i in range(10): ... funcs.append(lambda:i) ... [j() for j in funcs] [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
Tags (comma-separated)
Save Edits
Cancel