The for
statement creates variables.
for variable (, othervar, ....) in expression:
In this case, the expression
is something which returns pairs of values (so basically, a 2-tuple) and so for
can declare two variables and have them receive one value each, similarly to how you can say
symbol, symbol_count = "stack overflow", 42
In some more detail, symbols
in this case is apparently a dict
variable, and items()
loops over the keys and returns one key and its value in each iteration.
Quick demo:
>>> symbols = {"foo": 17, "bar": 42, "baz": 1427}
>>> for symbol, symbol_count in symbols.items():
... print("symbol:", symbol)
... print("count:", symbol_count)
...
symbol: foo
count: 17
symbol: bar
count: 42
symbol: baz
count: 1427
Because the for
loop creates a new variable named symbol_count
, it is now a local variable which shadows the global dict with the same name; the two are distinct and unrelated, other than in that they share the same name in two separate symbol tables. Perhaps also read up on global vs local scope in Python.