• An iterator enumerates elements of a collection. It is an object with a single method next () returning the next element or raising stopiteration.

• You get an iterator on obj via the new built-in function iter (obj), which calls obj._class_.__iter_().

• A collection may be its own iterator by implementing both_iter_() and next ().

• Built-in collections (lists, tuples, strings, dict) implement_iter_(); dictionaries (maps) enumerate their keys; files enumerates their lines.

• You can build a list or a tuple from an iterator, e.g. list (aniterator)

• Python implicitly uses iterators wherever it has to loop :

o for elt in collection:

o if elt in collection:

o when assigning tuples: x,y,z= collection

Was this article helpful?

0 0

Post a comment