Search code examples
pythonpython-3.xgenerator

Iterating or accessing a python generator with index


Is it possible to iterate over a python generator with index like a list or access a generator element through index

For example:

sample_list = [1,2,3,4]
for i in range(len(sample_list)): #iterating with index
   print (sample_list[i]) #accessing element through index

Solution

  • Are you familiar with the enumerate function?

    for i, value in enumerate(your_gen):
        print(i)
        print(value)