Search code examples
pythonincrementnested-loops

Python initializing variable in a nested loop


i want the the variable genCounter to reset to zero when the iteration of the inner loops has completed. however it returns the first value of genreSet and does not go farther to increment the genCounter variable. kawa is a genrator object. Thanks in advance..

kawa = self.getFile()
genList = []
genCounter = 0
for gen in self.genreSet:
  print(gen)
  if genCounter == 0 :
    for ids, row in enumerate(kawa):
      self.genres = row['genres']
      self.genresList = self.genres.split('|')
      for n in self.genresList:
        if gen == n:
          genCounter+=1
  print(genCounter)
  genCounter=0

and this is the result

Documentary
2471
Sci-Fi
0
War
0
Horror
0
Musical
0
Children
0
Mystery
0
Drama
0
IMAX
0
Action
0
Adventure
0
Fantasy
0
Crime
0
Comedy
0
(no genres listed)
0
Animation
0
Thriller
0
Romance
0
Western
0
Film-Noir
0

Solution

  • kawa is a generator object. Therefore, its becomes empty after the first call to

    enumerate(kawa)
    

    If you replace the first line of code with

    kawa = tuple(self.getFile())
    

    Then it probably will work. (Or at least yield a different bug ;)