I saw some code yesterday in this question that I had not seen before, this line in particular:
for xyz[num] in possible[num]:
...
So as this loop runs, the elements from possible[num] are assigned to the list xyz at position num. I was really confused by this so I did some tests, and here is some equivalent code that is a little more explicit:
for value in possible[num]:
xyz[num] = value
...
I definitely intend to always use this second format because I find the first more confusing than it is worth, but I was curious… so:
Is there any good reason to use this “feature”, and if not, why is it allowed?
Here are a couple of stupid use cases I came up with (stupid because there are much better ways to do the same thing), the first is for rotating the letters of the alphabet by 13 positions, and the second is for creating a dictionary that maps characters from rot13 to the character 13 positions away.
>>> import string
>>> rot13 = [None]*26
>>> for i, rot13[i%26] in enumerate(string.ascii_lowercase, 13): pass
...
>>> ''.join(rot13)
'nopqrstuvwxyzabcdefghijklm'
>>> rot13_dict = {}
>>> for k, rot13_dict[k] in zip(rot13, string.ascii_lowercase): pass
...
>>> print json.dumps(rot13_dict, sort_keys=True)
{"a": "n", "b": "o", "c": "p", "d": "q", "e": "r", "f": "s", "g": "t", "h": "u", "i": "v", "j": "w", "k": "x", "l": "y", "m": "z", "n": "a", "o": "b", "p": "c", "q": "d", "r": "e", "s": "f", "t": "g", "u": "h", "v": "i", "w": "j", "x": "k", "y": "l", "z": "m"}
The reason this is allowed is simplicity. The list of “loop variables” has the same grammar as any other assignment target. As an example, tuple unpacking is allowed in assignments, so it is allowed in
forloops as well, and this is certainly quite useful. Defining a separate syntax for the assignement of loop variables would seem artificial to me — the semantics of regular assignment and loop variable assignments are the same.