These two code segments should be printing out the same thing right? However, the top part with the defaultdict is going from 1 to 4 instead of 1 to 3. I tested the same for-loop structure below with just integers and got what I expected (1 to 3). Can somebody explain what is going on here? It should always print out the default value since I am not assigning any values in the dictionary. So shouldn't it print out 3 first? Python Code image
Asked
Active
Viewed 20 times
-2
-
**Do not post images of code**. Post all code as formatted text in the question itself. – juanpa.arrivillaga May 31 '22 at 02:57
-
1Names in the body of a `lambda` get looked up *at the time the lambda is called*, not when it was defined. The first lambda is defined when i=3, but isn't called until the next iteration of the loop, when I=4, so that's the value it returns. The usual trick to work around this is to capture the name as a default parameter: `lambda x=i: x` for example. – jasonharper May 31 '22 at 02:58
-
In any case, no, `lambda : i` is referring to `i` the global variable. In the first iteration, you actually hardcode `lambda: 1`, so of course `d[whatever]` gives you `1`, in the **next iteration**, where `i == 4`, it prints `4`. Why did you expect it to print `3`? Try printing `i` – juanpa.arrivillaga May 31 '22 at 02:59
-
"Is this a glitch in Python's defaultdict?" Most likely not. You should show some code to go with your verbal description. Post code as text, not as a screenshot. – Code-Apprentice May 31 '22 at 03:02
-
I thought it would print 3 because the defaultdict was assigned a default value when i = 3 at the beginning of the loop. But now I understand why. Thank you so much! – Jerry He May 31 '22 at 03:05