If inside a loop, is it possible to instantiate objects to be manipulated during subsequent iterations of the loop, and still available when the scope of the loop has been left?
Here is a simple example of what I thought might work:
>>> for i in range(2):
... r = [] if r is None else r
... r.append[i]
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'r' is not defined
And here’s my second attempt using a NameError exception:
>>> for i in range(2):
... try:
... r = r
... except NameError:
... r = []
... r.append(i)
...
>>>
I suspect that what I have been trying to do is actually prohibited, but I don’t understand why it would be.
Can someone throw some light on this for me please?
Edit:
So the second way works, but it’s very long winded. Is there a quick way?
You can find out if the name is in your locals like this:
name in locals()Regarding your question:I agree with Ignacio Vazquez-Abrams; this is not good style. Please do what you need to before looping.