Q:

For loop in python initializes an outer variable on each iteration

I can't understand why the following codes gives different results:
from datetime import datetime

def foo():
    return {datetime.now() : True}

a = {}
a.update(foo())
a.update(foo())
a.update(foo())

And:
a = {}
for i in xrange(3):
    a.update(foo())

In the former a ends up with three elements, while in the later a ends up with just one element (from the last iteration).

A:

Just your luck. The second code is likely to execute in a single millisecond (or microsecond, depending on your OS), and give three identical datetimes, first is less likely to do so (on your system/your way of executing code). Keep trying, you might end up with two elements. Don't write code that depends on luck.

A:

The number of elements you end up with will depend on how many calls to foo Python executes within the granularity of datetime.now().
If you're running this in an interactive console then between statements executed at the prompt the console will perform housekeeping (for example, displaying the >>> prompt) that will significantly delay the next statement, whereas for the for loop the loop will be executed in its entirety before the console does anything.

