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

前端 未结 5 1172
渐次进展
渐次进展 2020-12-10 11:45

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

5条回答
  •  醉酒成梦
    2020-12-10 12:37

    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.

提交回复
热议问题