Is the following code bad practice?
for i in some_values:
do_whatever(i)
do_more_things(i)
Somehow, it feels to me like the variable i
should remain in the scope to the block inside the for-loop. However python 2.7 lets me reuse it after the loop.
Does python officially supports that feature, or am I abusing the language?
In Python, we may reuse the same variable to store values of any type. A variable is similar to the memory functionality found in most calculators, in that it holds one value which can be retrieved many times, and that storing a new value erases the old.
Is it okay to create multiple for loops with the same variable name? Yes, it's OK and widespread practice to do so.
In Python variables have function-wide scope which means that if two variables have the same name in the same scope, they are in fact one variable. Consequently, nested loops in which the target variables have the same name in fact share a single variable.
Yes, it's official:
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
> The target list is not deleted when the loop is finished
http://docs.python.org/reference/compound_stmts.html#for
Note that a target list after for
is far more than just a variable:
for some_list[blah] in...
for some_object.foo in...
for a[:n] in ...:
etc. These things cannot simply disappear after the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With