1
def foo():
    lst = []
    for i in range(4):
        lst.append(lambda: i)
        print(lst[i]())
    print([f() for f in lst])
foo()

this is the output for above code

0
1
2
3
[3, 3, 3, 3]

why the lst inside the for loop is printing [0,4) and lst outside the for loop is printing [3,3,3,3]

pavan kumar
  • 125
  • 3
  • 10
  • 3
    Possible duplicate of [What do (lambda) function closures capture?](https://stackoverflow.com/questions/2295290/what-do-lambda-function-closures-capture) – Joseph Sible-Reinstate Monica Sep 29 '19 at 02:07
  • 1
    in a nutshell: because the lambda refers to the value of the variable `i` _when the lambda is called_, and after the loop this value is `3` – njzk2 Sep 29 '19 at 02:11
  • Best explanation [Late-binding closures](https://docs.python-guide.org/writing/gotchas/#late-binding-closures) – askaroni Sep 29 '19 at 02:16

0 Answers0