Day 2: Clever Stuff Python Challenge: late-binding presents
Read this slide as text
Late-binding presents. Clever Stuff Python Challenge. What would the output be? Extra point for spotting the bug. The code, in a file called gifts.py: gifts = [lambda: i for i in range(3)], then print([g() for g in gifts]).
Reveal the answer
The output is [2, 2, 2]. The bug: each lambda looks up i when it is called. By then the loop has finished and i is 2. The fix: [lambda i=i: i for i in range(3)], which gives [0, 1, 2].
![Late-binding presents. Clever Stuff Python Challenge. What would the output be? Extra point for spotting the bug. The code, in a file called gifts.py: gifts = [lambda: i for i in range(3)], then print([g() for g in gifts]).](/_astro/slide-1.2Wbx9H_Z_Z2pQ3hN.png)