Search code examples
pythonlistenumeration

Iterating Enumeration Object Two Times


I created an enumeration object, and I iterated a list by means of the enumeration. After that, I tried to do it second time and I could not take any output in the interpreter.

myList = ["Red", "Blue", "Green", "Yellow"]
enum = enumerate(myList, 0)

for i in enum:  # this printed the output
    print(i)

for j in enum:  # this did not print the output
    print(j)

Why could not I use enum object two times ?


Solution

  • enumerate is an iterator, which means that once it is operated on a single i.e looped over or next called, its references to values in memory have been exhausted, thus, a mere empty list ([]) will be the result the second time next is called on the structure, or for applied.

    However, to solve this problem, you can either cast the result as a list, or add the contents to another list:

    val = iter([i**2 for i in range(10)])
    new_result = list(val)
    >>>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    #create a new structure: 
    val = iter([i**2 for i in range(10)])
    other_val = [ for i in val]
    

    Or, applying next:

    val = iter([i**2 for i in range(10)])
    while True: 
       try:
         v = next(val)
         #do something with v
       except StopIteration:
         break