In Python what is the difference between an iterable and an iterator?

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

An iterable (like a list, tuple, dictionary) are objects that returns an Iterator if you call iter() on it. That means that an iterable must implement the __iter__ method.

An iterator returns data one at a time whenever next() is called on it. That means that an iterator must implement the __next__ method. Many iterators are also iterable.

A list is iterable but not an iterator. But it you call iter() passing it the list, iter() will return an iterator.

my_list = ['alpha', 'beta', 'gamma']
my_iterator = iter(my_list)
print(my_iterator)
# <list_iterator object at 0x10f873048>

This means that we can run next() on our iterator…

answer = next(my_iterator)
print(answer) # alpha

answer = next(my_iterator)
print(answer) # beta

answer = next(my_iterator)
print(answer) # gamma

answer = next(my_iterator)
print(answer) # StopIteration Exception

When it runs out of values, the iterator throws an StopIteration exception.

A generator function is a function that has an “yield” instead of a “return”. The generator function produces a iterator (or a generator iterator).


Related Posts

Tags

Share This