Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does python officially support reusing a loop-variable after the loop?

Tags:

python

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?

like image 861
Niriel Avatar asked May 12 '12 12:05

Niriel


People also ask

Can I reuse variables in Python?

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.

Can you use the same variable for two loops?

Is it okay to create multiple for loops with the same variable name? Yes, it's OK and widespread practice to do so.

Can I use same variable for different for loops in Python?

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.


1 Answers

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.

like image 181
georg Avatar answered Sep 19 '22 15:09

georg