title: How do I create a list of lambdas (in a list comprehension/for loop)?
body: <p>I want to create a list of lambda objects from a list of constants in Python; for instance:</p>
  
  <pre><code>listOfNumbers = [1,2,3,4,5]
  square = lambda x: x * x
  listOfLambdas = [lambda: square(i) for i in listOfNumbers]
  </code></pre>
  
  <p>This will create a list of lambda objects, however, when I run them:</p>
  
  <pre><code>for f in listOfLambdas:
      print f(),
  </code></pre>
  
  <p>I would expect that it would print</p>
  
  <pre><code>1 4 9 16 25
  </code></pre>
  
  <p>Instead, it prints:</p>
  
  <pre><code>25 25 25 25 25
  </code></pre>
  
  <p>It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.</p>
  
  <p>EDIT: a bit more of trying things and such came up with this:</p>
  
  <pre><code>listOfLambdas = []
  for num in listOfNumbers:
      action = lambda: square(num)
      listOfLambdas.append(action)
      print action()
  </code></pre>
  
  <p>Prints the expected squares from 1 to 25, but then using the earlier print statement:</p>
  
  <pre><code>for f in listOfLambdas:
      print f(),
  </code></pre>
  
  <p>still gives me all <code>25</code>s. How did the existing lambda objects change between those two print calls?</p>
  
  <p>Related question: <a href="https://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different">Why results of map() and list comprehension are different?</a></p>