Iteration in python

Hi. Im on the subject of Iteration but I can’t seem to wrap my head around it. Why not just use a for-loop?
Why go through the trouble of writing an entire class to do the same thing? Is it that you can do more? If so, what are the benefits and exactly how do you it? Can you explain this code for example:

class misc:
    def __iter__(self):
        self.a = 0
        return self

    def __next__(self):
        x= self.a
        self.a += 2
        return x


myiter = iter(misc())

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

I worte this myself off the internet but some things are not clear to me.

  1. Why do we return self in def iter ?
  2. why can we not use x instead of self.a in += 2?
  3. How can iuse this class in other forms than numbers?

You wouldn’t write an iterable class for a simple case like this. It’s more about making your own classes work with Python’s for-loop when it makes sense.

Imagine you have a class for a deck of playing cards, and you want to be able to write something like this:

for card in deck:
    print(card)

Here it makes sense to define the magic __iter__ method as sort of an adapter to the language construct.


Now, on a more technical level, there are two closely related concepts in Python that you need to understand when writing your own iteratables:

  1. An iterable is any object that you can use in a for-loop. Under the hood, an iterable is any object that defines an __iter__ method which returns an iterator.

  2. An iterator is any object that defines both an __iter__ method which returns the object itself, and a __next__ method, which keeps some sort of internal state and returns the next element of a sequence each time it’s called, until no elements are left.

An iterable provides iteration behavior, either by being an iterator itself or by providing a distinct iterator object on request. The iterator implements the iteration behavior. Like in your example, every iterator is an iterable, meaning you can use it in a for loop. (Not every iterable is an iterator though.)


I wouldn’t worry too much about this for now. It’ll be handy to know this stuff when you start working with classes a lot.

2 Likes

Exactly right, but I’ll add that if you make your iter style object correct then you can do this:

myiter = misc()
for x in myiter:
   print(x)

The point of this is to let you do fake for-loops on things that aren’t traditionally iterable.