Python – Iterators

One of the benefits of having your own blog and not following any schedule for subjects to write about is that you may write for whatever you feel like, whenever you feel like. So, Iterations in Python is the subject of the today’s article.

Iterators are classes, which generate some sequence of values. These are the classes which we may see in the for each loops – for element in object

To convert a class into iterator, e.g. to make sure that we may loop through its elements, we need only two dunder methods – __iter__(self) and __next__(self) . And that’s it – your class is iterator and its objects could be looped over! A bit about each method here:

  • __iter__ (self) – this is the method that would return an element of the class. Plus, this is literally the method, that makes the class iterable.
  • __next__(self) – this method is run on each iteration and should give the next element of the sequence. The exception StopIteration is a must when this method is implemented.

Now the example – imagive that you need to implement a class, mirroring the strings that are given to you. E.g. “VitoshAcademy” becomes “ymedacAhsotiVVitoshAcademy” and “1234” becomes “12344321”. Fair enough, but without using the Reverse built-in function, of course.

This is my solution:

And this is how you call the class:

Tagged with: ,