Python list comprehension with dummy names identical to iterator name: ill-advised?
dictionary-comprehension, list-comprehension, python, python-3.x
Solution
TL;DR: It is safe, technically, but it's a poor choice stylistically.
In a list comprehension, before binding the free variable of the for-loop to any object, Python will use a `GET_ITER` opcode on the iterable to get an iterator. This is done just once at the beginning of the loop.
Therefore in the body of the "loop" of the list comprehension (which actually creates a scope in Python 3), you may rebind the name which originally pointed to the iterable without any consequence. The iteration deals with a reference to the iterator directly, and whether or not it has a name in scope is irrelevant. The same should hold true in Python 2, though the scoping implementation details are different: the name of the collection will be lost after the comprehension, as the loop variable name will remain bound to the final element of iteration.
There is no advantage to writing the code in this way, and it is less readable than just avoiding the name collision. So, you should prefer to name the collection so that it more obvious that it is a collection:
[f(x) for x in xs]
Problem
Say I make a list comprehension that looks something like this: ``` i = range(5) a = [f(i) for i in i] ``` for some function `f`. Will using a dummy name identical to the iterator ever yield unexpected results? Sometimes I have variable names that are individual letters, and to me it is more readable to stick with the same letter rather than assigning a new one, like `[f(x) for x in x]` instead of `[f(i) for i in x]` (for instance, if the letter of the iterator `x` is meaningful, I will wonder what the heck `i` is).