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?

TommyGEB
  • 33
  • 3

2 Answers2

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.

Alex Shkop
  • 1,992
  • 12
  • 12
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)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502