25

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?

2
  • hmmm... seems like this might be ok since it is used here Commented May 12, 2012 at 12:23
  • 2
    There are a fair number of use-cases which benefit from accessing the last value of a loop variable in subsequent code Commented May 12, 2012 at 12:28

5 Answers 5

22

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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.

10 Comments

Who doesn't recommend it? And why would it make the code difficult to read - python variables exist throughout their scope, however they are introduced.
I agree. It just feels "dirty".
First of all, I believe it makes an assumption that the loop is ran and the variable indeed assigned. Secondly, when reading this as a third-person, I would assume the variables defined on the same/lower indent. But python community is divided on this one.
"I would assume the variables defined on the same/lower indent" Why would you assume that?
@Marcin I am sorry - I cannot quote any rule on that. This stems from my personal experience. As I have clarified - the python community is a bit divided on this one and I would be up for loops having their own scope. But I suppose I may be a minority on that one :)
|
5

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)

Comments

1

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.

Comments

-1

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

1 Comment

Hmm, I downvoted this because "That's not a feature" seems to directly contradict the top answer, but now re-reading the question I think you mean "it's not a feature that i only lasts for the loop scope" which is true. I'm going to leave the downvote there though, because I think your wording is unclear and the interpretation I first had was the more natural one (and wrong).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.