The following points apply to all collections, defined in the library or by the user: This rule does not imply that indices should be cheap to convert to actual integers.

The offsets for consecutive elements could be non-consecutive (e.g., in a hash table with open addressing), or consist of multiple offsets so that the conversion to an integer is non-trival (e.g., in a tree).

In C , validity of an iterator is a property of the iterator itself, since iterators can be dereferenced to access collection elements.

invalidating iterator-32

By contrast with a subroutine, a generator coroutine can yield values to its caller multiple times, instead of returning just once.

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.

There are subtle differences and distinctions in the use of the terms "generator" and "iterator", which vary between authors and languages.

Some object-oriented languages such as C#, C (later versions), Delphi (later versions), Go, Java (later versions), Lua, Perl, Python, Ruby provide an intrinsic way of iterating through the elements of a container object without the introduction of an explicit iterator object.

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.

Several languages, such as Perl and Python, implement streams as iterators.

Alternative implementations of stream include data-driven languages, such as AWK and sed.

Note that an iterator performs traversal and also gives access to data elements in a container, but does not perform iteration (i.e., not without some significant liberty taken with that concept or with trivial use of the terminology).

An iterator is behaviorally similar to a database cursor.

Depending on the language and intended use, iterators may also provide additional operations or exhibit different behaviors.