3

I was trying to create a list of lambda functions for a list of strings.

columns = ['a', 'b', 'c']
formats = []
for i, v in enumerate(columns)
    formats.append(lambda x: str(i + 1) + '%4f' %x)

and the output of formats[0](12) was supposed to be 1:12.0000

but the result turns out that no mater I use formats[0](13), formats[1](26) or formats[2](12), the output is always like 3:##.####.

It seems that it always keep the format of the last loop. Why? Could anyone help?

0

2 Answers 2

2

See http://www.toptal.com/python/top-10-mistakes-that-python-programmers-make error #6. Python binds variables in closures when function is called, not when it is defined.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! exactly the same problem. Really helpful.
1

This is because the value of i isn't bound to the lambda at creation time. One way to get around this is to pass it in as a default argument

formats.append(lambda x, i=i: str(i + 1) + '%4f' %x)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.