Can't figure out the iterations. Fulfills 2 times, as it should, but returns the entire list. According to the documentation, as I understand it, it should process each element of the list. I have already tried to create another loop inside __next__ , in general it does not work. Need to handle list items where I made a mistake?

 class Valuefilter(object): def __init__(self, *args): self.list_data = args self.num = 0 def __iter__(self): return self def __next__(self): if self.num != 2: self.num += 1 for x in self.list_data: return x else: raise StopIteration args = [33, 12, 17, 88, 4] iter = Valuefilter(*args) for i in iter: print(i) 
  • It is written in your __next__ to return the first element of the list exactly two times - this is what happens to me and printed 33 two times. What did you really want to implement with this code, I could not understand - andreymal
  • describe in words what the code should do; give an explicit example of the desired I / O. Explicitly describe how the actual output from yours is different - jfs
  • I wanted to be displayed like this: 33, 12, 17, 88, 4. The element is inside the list and each of them has its own iterator, if I understood everything correctly - S. Dior
  • @ S.Dior do you want to print(*args, sep=', ') to write? How the result of calling print is different from what you want¶ Do not put the information you need to answer in the comments, update your question instead. Click Edit - jfs

1 answer 1

As far as I understand you, you need to do something like this:

 def __iter__(self): for _ in range(2): yield from self.list_data 
  • Replace the code in question with: print(*itertools.repeat(args, 2)) , at least you can use yield from self.list_data in your yield from self.list_data There is a subtle difference: iter(it) is it broken (the difference between the iterator in particular and iterable in general). - jfs