0

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
data_person
  • 4,194
  • 7
  • 40
  • 75
  • Related: [Get the nth item of a generator in Python](https://stackoverflow.com/questions/2300756/get-the-nth-item-of-a-generator-in-python) – Brian61354270 Apr 08 '21 at 02:12
  • @Brian Thanks for the response. Its more of accessing it with a given index, I am looking to iterate through it with ```index```. I will check if I can use that. – data_person Apr 08 '21 at 02:15
  • Could you comment why you want to index a generator? Do you want to have access to an index while you're consuming it? Or do you want to skip the first n-1 yielded values to immediately get the nth? Or something else? – Brian61354270 Apr 08 '21 at 02:19
  • @Brian check for a ```value``` at index ```i``` if it certifies a ```condition``` I want to access ```i+1``` or skip ```i+1``` and go to ```i+2``` – data_person Apr 08 '21 at 02:30

1 Answers1

3

Are you familiar with the enumerate function?

for i, value in enumerate(your_gen):
    print(i)
    print(value)
ubershmekel
  • 11,864
  • 10
  • 72
  • 89