DEV Community

Discussion on: What Did You Learn This Week --April 24?

Collapse
 
waylonwalker profile image
Waylon Walker • Edited

This week I learned about binding default values to dynamically created lambdas in python.

## WRONG 💥
files = ['abc', 'def', 'ghi', 'jkl']
funcs = []
for file in files:
   funcs.append(lambda: print(file))
funcs[0]()

😲 This prints 'jkl'. in fact every function prints 'jkl', they just print the latest value of 'jkl'

## CORRECT 🎉
files = ['abc', 'def', 'ghi', 'jkl']
funcs = []
for file in files:
   funcs.append(lambda x=file: print(x))
funcs[0]()

Now this is more of what I was looking for. The value of file was bound to the lambda upon creation, and will print out each value of the list as intended... Hard lesson learned this week.