I have a C++ background and I'm learning Python. I am writing code which needs to extract a particular value from a for
loop:
seventh_value = None # ** my question is about this line
for index in range(1, 10):
value = f(index)
# we have a special interest in the seventh value
if index == 7:
seventh_value = value
# (do other things with value here)
# make use of seventh_value here
In C++ I'd need to declare seventh_value before the for loop to ensure its scope is not limited to the for loop. In Python I do not need to do this. My question is whether it's good style to omit the initial assignment to seventh_value.
I understand that if the loop doesn't iterate at least 7 times then I can avoid a NameError by assigning to seventh_value prior to the loop. Let's assume that it is clear it will iterate at least 7 times (as in the above example where I've hard-coded 10 iterations).
I also understand that there may be other ways to extract a particular value from an iteration. I'm really just wondering about whether it's good style to introduce variables before a loop if they will be used after the loop.
The code I wrote above looks clear to me, but I think I'm just seeing it with C++ eyes.