2

I came across this code which is one of Python's gotchas:

def create_multipliers():
    return [lambda x : i * x for i in range(5)]
for multiplier in create_multipliers():
    print multiplier(2)

I read the solution here but I am confused at some places. I have two questions:

  1. Why is it printing 8,8,8,8,8 instead of 0,2,4,6,8?

  2. They come up with this solution

    def create_multipliers():
        return [lambda x, i=i : i * x for i in range(5)]
    

    What is i=i doing and why it used?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
micro192
  • 87
  • 1
  • 4
  • Your link is literally to `http://here`, which isn't terribly helpful. – jonrsharpe Oct 09 '16 at 08:07
  • @jonrsharpe its not duplicate sir , please don't mark it duplicate – micro192 Oct 09 '16 at 08:28
  • 1. That link still wasn't right, but I fixed it. 2. Absolutely it's a duplicate. See also http://stackoverflow.com/q/17677649/3001761. You are talking about the same behaviour and the existing answers explain everything. – jonrsharpe Oct 09 '16 at 08:30
  • If, having read all the answers on the two linked questions, you *still* have a question, please [edit] to make it clear what that question is and how the information you already have fails to answer it. – jonrsharpe Oct 09 '16 at 08:43
  • @jonrsharpe i didn't understand that explanation please remove duplicate :/ – micro192 Oct 09 '16 at 08:46
  • @micro192 Edit your question with a more detailed explanation of what you don't understand. – dkasak Oct 09 '16 at 08:48
  • No, that's not a good reason. What **precisely** do you still not understand? And if you can't understand the existing answers, why do you think another answer will help at all? – jonrsharpe Oct 09 '16 at 08:49

0 Answers0