Why are arbitrary target expressions allowed in for-loops?

Viewed 3044

I accidentally wrote some code like this:

foo = [42]
k = {'c': 'd'}

for k['z'] in foo:  # Huh??
    print k

But to my surprise, this was not a syntax error. Instead, it prints {'c': 'd', 'z': 42}.

My guess is that the code is translated literally to something like:

i = iter(foo)
while True:
    try:
        k['z'] = i.next()  # literally translated to assignment; modifies k!
        print k
    except StopIteration:
        break

But... why is this allowed by the language? I would expect only single identifiers and tuples of identifiers should be allowed in the for-stmt's target expression. Is there any situation in which this is actually useful, not just a weird gotcha?

4 Answers
Related