- There is one further shortcut we could adopt. Suppose we wanted to create a set of items, such as in the "list_of_email_addrs" example above. Here, we're simply taking the target of the for loop and turning that into the key for the dict comprehension.
Hm, I don't like this. I think it's confusing: you really have to think about whether {x for x in <whatever>} produces a dictionary whose keys are in <whatever> or one whose values are in <whatever>.
- Should nested for loops be allowed? The following example, taken from an earlier revision of this PEP illustrates the problem:
>>> print {k, v for k in range(4) for v in range(-4, 0, 1)}
Don't you mean {k: v for ...}? The second range() also seems like you meant range(0, -4, -1).
The intent of this example was to produce a mapping from a number to its negative, but this code doesn't work because -- as in list comprehensions -- the for loops are nested, not in parallel! So the value of this expression is actually
{0: -1, 1: -1, 2: -1, 3: -1}
which seems of dubious value. For symmetry with list comprehensions, perhaps this should be allowed, but it might be better to disallow this syntax.
Nested for loops can be useful when used properly: {(k, v): k+v for k in range(4) for v in range(4)} Your example should have been expressed using: {k: v for k, v in zip(range(4), range(0, -4, -1))} --Guido van Rossum (home page: http://www.python.org/~guido/)