You only need to implement the following methods:

  • __iter__()
  • __next__()

Example

for b in Basket('potato', 'apple', 'cheese'):
  print(b)

-> potato
-> apple
-> cheese

Code

Using list.pop():

class Basket:
  def __init__(self, *arg):
    self._list = list(arg)
    self._list.reverse()
    
  def __iter__(self):
    return self
  
  def __next__(self):
    if len(self._list) == 0:
      raise StopIteration()
    return self._list.pop()

Without list.pop():

class Basket:
   def __init__(self, *arg):
      self._list = list(arg)
      self._index = len(self._list)
      self._list.reverse()

   def __iter__(self):
       return self

   def __next__(self):
      self._index -= 1

      if self._index < 0:
         raise StopIteration()

      return self._list[self._index]

Sequence diagram

  1. Python calls Basket’s iter() method
  2. Basket calls it’s __iter__() magic method…
  3. …which just returns itself
  4. From here on, Python will be calling Basket’s next() method in a loop
  5. …which in turn causes Basket to call its __next__() magic method
  6. …which returns the element
  7. When there is no more element, the process stops through StopIteration exception