Search code examples
pythonfor-loopiterationenumerate

Reusing Iterator Variables in Python For Loops


In Python v2.7.3, can I reuse an iterator variable like this?

for i, name in enumerate(listOfNames):
   ...

and then later do:

for i, address in enumerate (addressList):
   ...

Solution

  • What iterator variable? You aren't re-using anything. You are calling enumerate two separate times, so it will produce two separate generators.

    The only way you'd get into trouble is if you did something like this

    >>> listOfNames = ['bob', 'mike', 'steve']
    >>> e = enumerate(listOfNames)
    
    >>> for i, name in e:
            print(i)
    
    0
    1
    2
    
    >>> for i, name in e:
            print(i)
    
    # prints nothing
    

    Note that we assigned the return value of the enumerate call to a variable e. If you try to iterate over that variable twice, you will get nothing the second time. In your case, you will not run into this issue