Differences between revisions 3 and 4
Revision 3 as of 2008-11-15 14:01:03
Size: 2136
Editor: localhost
Comment: converted to 1.6 markup
Revision 4 as of 2018-03-08 15:38:21
Size: 2121
Editor: NoahInada
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
An '''iterable''' object is an object that implements {{{__iter__}}}. {{{__iter__}}} is expected to return an '''iterator''' object. An '''iterable''' object is an object that implements {{{__iter__}}}, which is expected to return an '''iterator''' object.
Line 3: Line 3:
An '''iterator''' is an object that implements {{{next}}}. {{{next}}} is expected to return the next element of the iterable object that returned it, and raise a {{{StopIteration}}} exception when no more elements are available. An '''iterator''' is an object that implements {{{next}}}, which is expected to return the next element of the iterable object that returned it, and raise a {{{StopIteration}}} exception when no more elements are available.

An iterable object is an object that implements __iter__, which is expected to return an iterator object.

An iterator is an object that implements next, which is expected to return the next element of the iterable object that returned it, and raise a StopIteration exception when no more elements are available.

In the simplest case the iterable will implement next itself and return self in __iter__.

You can use iterables in for loops, and you can use them to construct lists.

Example Iterator

Here is an iterator that returns a random number of 1's:

   1 import random
   2 
   3 class RandomIterable:
   4     def __iter__(self):
   5         return self
   6     def next(self):
   7         if random.choice(["go", "go", "stop"]) == "stop":
   8             raise StopIteration  # signals "the end"
   9         return 1

Q: Why is __iter__ there, if it just returns self?

A: This is a very simple case. More complex iterables may very well return separate iterator objects.

Q: When would I need an extra iterator?

A: Iterator will typically need to maintain some kind of position state information (like the index of the last element returned or the like). If the iterable maintained that state itself, it would become inherently non-reentrant (meaning you could use it only one loop at a time).

   1 for eggs in RandomIterable():
   2     print eggs

You can also use it in list construction:

   1 >>> list(RandomIterable())
   2 [1]
   3 >>> list(RandomIterable())
   4 []
   5 >>> list(RandomIterable())
   6 [1, 1, 1, 1, 1]
   7 >>> list(RandomIterable())
   8 [1]

...both of these uses require __iter__.

An object isn't iterable unless it provides __iter__. And for an object to be a valid iterator, it must provide next.

See also: Generators

Discussion

  • (none yet!)

Iterator (last edited 2021-12-11 12:50:13 by ChrisM)

Unable to edit the page? See the FrontPage for instructions.