title: Python class and __iter__
body: <p>What are the benefits of using the <code>__iter__</code> function in a Python class?</p>
  
  <p>In the code below I am just setting up two simple classes. The first class takes in a list as an argument, and I am able to loop over this list without using the <code>__iter__</code> function. The second bit of code uses the <code>__iter__</code> function to loop over a list.</p>
  
  <p>What is the benefit of using <code>__iter__</code> when there are already ways of looping over stuff in a class?</p>
  
  <pre><code>EG 1: no __iter__
  
  
  class test_class:
      def __init__(self, list):
          self.container_list = list
  
      def print (self):
          a = self.container_list
          return a
  
  test_list = test_class([1,2,3,4,5,6,7])
  
  x = test_class.print(test_list)
  
  for i in x:
      print (i)
  
  
  
  EG 2: yes __iter__
  
  class list_using_iter:
      def __init__(self):
          self.list = [1,2,3,4]
          self.index = -1
  
      def __iter__(self):
          return self
  
      def __next__(self):
          self.index += 1
          if self.index == len(self.list):
              raise StopIteration
          return self.list [self.index]
  
  r = list_using_iter()
  itr = iter(r)
  
  print(next(itr))
  print(next(itr))
  print(next(itr))
  print(next(itr))
  
  print(next(itr)) # Raises the exception!
  </code></pre>