notrockstar
notrockstar

Reputation: 853

for/if loops and a scope of the variable in python

I am confused about the scope of the variable in python. Here is a toy example of what I am trying to do:

a = True
enumerated_set = enumerate(['tic','tac','toe'])
for i,j in enumerated_set:
    if a == True:
        print j

The result I get is:

tic
tac
toe

now,

print a

returns

`True`

and if I ran again

for i,j in enumerated_set:
    if a == True:
        print j

I get no output.

I am confused... Since globally a = True, why during the second loop the print was not executed.

I appreciate your help.

Edit: another example where I am confused

y = 'I like this weather'.split()
for item in y:
    for i,j in enumerated_set:
         if a == True: 
             print j

also produces no output....

Upvotes: 2

Views: 130

Answers (3)

jkalivas
jkalivas

Reputation: 1163

It is nothing to do with the a variable. You are using an enumerator object,and in the first loop it is gone to its end. You have to recreate it for the second loop.

Upvotes: 1

spencer nelson
spencer nelson

Reputation: 4525

This is not due to scope, it is due to the nature of enumerate, which creates a generator, not a list. Generators are single-use: they pop off elements in sequence, they don't create a list which can be evaluated again. This saves memory.

If you wanted to iterate over enumerated_set twice, you might do this:

enumerated_set = list(enumerate(['tic','tac','toe']))

Upvotes: 1

jdi
jdi

Reputation: 92559

It is actually not a problem with your boolean. That is always True.

enumerated_set is a generator. Once you cycle through it, it is exhausted. You would need to create a new one.

In [9]: enumerated_set = enumerate(['tic','tac','toe'])

In [10]: enumerated_set.next()
Out[10]: (0, 'tic')

In [11]: enumerated_set.next()
Out[11]: (1, 'tac')

In [12]: enumerated_set.next()
Out[12]: (2, 'toe')

In [13]: enumerated_set.next()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
/usr/local/<ipython-input-13-7b0a413e4250> in <module>()
----> 1 enumerated_set.next()

StopIteration: 

Upvotes: 7

Related Questions