When I run the following script, both lambda’s run os.startfile() on the same file — junk.txt. I would expect each lambda to use the value “f” was set to when the lambda was created. Is there a way to get this to function as I expect?
import os
def main():
files = [r'C:\_local\test.txt', r'C:\_local\junk.txt']
funcs = []
for f in files:
funcs.append(lambda: os.startfile(f))
print funcs
funcs[0]()
funcs[1]()
if __name__ == '__main__':
main()
One way is to do this:
Otherwise
fis looked up when the function is called, so you get the current (after the loop) value.Ways I like better:
or even (in python 2.5+):