Any good use for assigning a list / dict during a loop?

I saw the code yesterday in this question , which I had not seen before, this line in particular:

for xyz[num] in possible[num]: ... 

Since this loop works, elements from possible[num] assigned to the xyz list at position num . I was really confused by this, so I did some tests, and here are some equivalent codes that are a bit more explicit:

 for value in possible[num]: xyz[num] = value ... 

I definitely intend to always use this second format, because I find the first one more confusing than it's worth it, but I was curious ... like this:

Is there a good reason to use this "feature", and if not, why is it allowed?

Here are some silly use cases that I came up with (silly because there are much better ways to do the same), the first is to rotate the letters of the alphabet by 13 positions, and the second to create a dictionary that displays characters from rot13 to 13 characters .

 >>> 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"} 
+6
source share
2 answers

The reason for this is simplicity. The list of "loop variables" has the same grammar as any other destination . For example, when assigning, tuples can be unpacked, so it is also allowed in for loops, and this is certainly very useful. The definition of a separate syntax for assigning loop variables seems artificial to me: the semantics of regular assignments and assignment of loop variables are the same.

+10
source

I think this is a matter of programming style, or no one is using this technique. It is clear that for prominent people it is not so obvious what a loop is at first glance. Therefore, I myself would prefer to use more understandable methods, especially if you want your code to be readable by other people who may not know much of the language.

However, this will be a breakthrough in the philosophy and mechanics of python, if such a design is not allowed. This can be clearly seen, since the loop takes a sequence (list or line) and iterates over each element that stores the current value in each iteration into the variable that must be specified. A variable is a reference to an object, and therefore it is obvious that it does not matter whether it is a temporary variable, an array field, or something else.

+3
source

Source: https://habr.com/ru/post/909028/


All Articles