0
x, *y, z = range(1,10)
k = ['x', 'y', 'z']
d = {k:v for k, v in zip(k, (x, y, z))}
for k in [*d]:
    print(f'{k}: {d[k]}')
print(k)
>>> z

The following works fine for k but it automatically assigns a which I do not desire.

x, *y, z = range(1,10)
k = ['x', 'y', 'z']
d = {k:v for k, v in zip(k, (x, y, z))}
for a in [*d]:
    print(f'{a}: {d[a]}')
print(k)
>>> ['x', 'y', 'z']
print(a)
>>> z

Question:

  1. Why k is 'z' instead of ['x', 'y', 'z']?
  2. What does for a in [*d] do?
  • 2
    Why do you think it should be `['x', 'y', 'z']` instead? – kaya3 Feb 11 '20 at 05:35
  • 1
    Does this answer your question? [What's the scope of a variable initialized in an if statement?](https://stackoverflow.com/questions/2829528/whats-the-scope-of-a-variable-initialized-in-an-if-statement) (slightly different question, but same answer). Or this? [Block scope in Python](https://stackoverflow.com/q/6167923/4518341) – wjandrea Feb 11 '20 at 05:41
  • 1
    This one specifically about the assignment target of the `for` loop: [Using for loop variable outside of the for loop](https://stackoverflow.com/questions/59296289/using-for-loop-variable-outside-of-the-for-loop/59296366#59296366) – kaya3 Feb 11 '20 at 05:43
  • so the `_` in `for _ in iterable` is not merely a placeholder but a legit pointer. It strikes me... Umm. –  Feb 11 '20 at 05:55
  • 1
    It's a variable. You use it inside the `for` loop's body no differently to any other variable. It just happens that because Python doesn't have block scope, the variable is still visible after the `for` loop. Using `_` as a name for a variable you ignore the value of is just a convention; it has no special significance in the language spec. – kaya3 Feb 11 '20 at 06:02

0 Answers0