Iterator vs Iterable vs Generator

suggest change

An iterable is an object that can return an iterator. Any object with state that has an __iter__ method and returns an iterator is an iterable. It may also be an object without state that implements a __getitem__ method. - The method can take indices (starting from zero) and raise an IndexError when the indices are no longer valid.

Python’s str class is an example of a __getitem__ iterable.

An Iterator is an object that produces the next value in a sequence when you call next(*object*) on some object. Moreover, any object with a __next__ method is an iterator. An iterator raises StopIteration after exhausting the iterator and cannot be re-used at this point.

Iterable classes:

Iterable classes define an __iter__ and a __next__ method. Example of an iterable class :

class MyIterable:

    def __iter__(self):

         return self

    def __next__(self):
         #code

#Classic iterable object in older versions of python, __getitem__ is still supported...
class MySequence:

    def __getitem__(self, index):

         if (condition):
             raise IndexError
         return (item)

 #Can produce a plain `iterator` instance by using iter(MySequence())

Trying to instantiate the abstract class from the collections module to better see this.

Example:

import collections
>>> collections.Iterator()
>>> TypeError: Cant instantiate abstract class Iterator with abstract methods next
>>> TypeError: Cant instantiate abstract class Iterator with abstract methods __next__

Handle Python 3 compatibility for iterable classes in Python 2 by doing the following:

class MyIterable(object): #or collections.Iterator, which I'd recommend....

     ....

     def __iter__(self): 

          return self
def next(self): #code

__next__ = next

Both of these are now iterators and can be looped through:

ex1 = MyIterableClass()
ex2 = MySequence()

for (item) in (ex1): #code
for (item) in (ex2): #code

Generators are simple ways to create iterators. A generator is an iterator and an iterator is an iterable.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Iterables and Iterators:
* Iterator vs Iterable vs Generator

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
80 Iterables and Iterators
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve