'Python: sum function with for loop: different results

Here is the code:

d = {1 : 1, 2 : 2, 3 : 2}
s, s1 = 0, 0
for e in d:
    s += sum(x for x in range(d[e]))
s1 = sum(sum(y for y in range(d[e])) for e in d)
print(f"s: {s}, s1: {s1}")

Why s == 2, but s1 == 3?

I expect s == s1 == 2.

It looks that interpreter knows an internal variable e from the for-loop prior the first run of the sum() function .



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source