Niriel
Niriel

Reputation: 2705

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

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?

Upvotes: 24

Views: 11235

Answers (5)

Ben Millwood
Ben Millwood

Reputation: 7011

You can use this technique to scan a list for items matching some criteria:

for item in iter:
    if interesting(item):
        break
else:
    raise ValueError('iter is boring.')

handle(item)

Upvotes: 5

Danosaure
Danosaure

Reputation: 3655

Just like @petr said, it sound unnatural. Not because it's allowed that it's natural or you have to use it.

I rather have something like this, although it may not apply to the logic with a break use-case:

for i in some_values:
    do_whatever(i)
else:
    do_more_things(i)

But this still raise NameError if some_values evaluate to empty, but sounds clearer. It does not give the clear readability of an inner scope but the indentation may suggests it.

But as other said, to answer to the specific OP's question, yes, it's legal.

Upvotes: 1

petr
petr

Reputation: 2586

Python can feel a bit special when it comes to scoping if you are coming from languages like C or Java. As previous answer says, the code is absolutely valid but I would recommend against it. It creates not particularly readable code and, furthermore, if some_values turns out to be empty, there will be an exception raised on the last line of the code.

So answer to your question is - yes, it is officially supported but in most cases it is not recommended strategy.

Interesting discussion can be found here and also local discussion on SO.

Upvotes: 7

georg
georg

Reputation: 215029

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.

Upvotes: 22

Maksym Polshcha
Maksym Polshcha

Reputation: 18368

That's not a feature. As you wrote the variable remains in the scope. It's normal interpreter behavior.

Upvotes: -1

Related Questions