This allows the container to store elements in any manner it wishes while allowing the user to treat it as if it were a simple sequence or list.An iterator class is usually designed in tight coordination with the corresponding container class.Thus, index is valid or not only in context of a certain collection instance at a certain point of program execution.A given index can be valid for zero, one or more than one collection instance at the same time.Depending on the language and intended use, iterators may also provide additional operations or exhibit different behaviors.The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container.An actual iterator object may exist in reality, but if it does it is not exposed within the source code of the language.
Most iterators are naturally expressible as generators, but because generators preserve their local state between invocations, they're particularly well-suited for complicated, stateful iterators, such as tree traversers.
Or other times they may be created by the collection object itself, as in this Ruby example: This iteration style is sometimes called "internal iteration" because its code fully executes within the context of the iterable object (that controls all aspects of iteration), and the programmer only provides the operation to execute at each step (using an anonymous function).
Languages that support list comprehensions or similar constructs may also make use of implicit iterators during the construction of the result list, as in Python: Iterators are a useful abstraction of input streams – they provide a potentially infinite iterable (but not necessarily indexable) object.
In procedural languages it is common to use the subscript operator and a loop counter to loop through all the elements in a sequence such as an array.
Although indexing may also be used with some object-oriented containers, the use of iterators may have some advantages: The ability of a container to be modified while iterating through its elements has become necessary in modern object-oriented programming, where the interrelationships between objects and the effects of operations may not be obvious.