Differencebetween Iterator and Iterable and How to Use Them

What is the difference between iterator and iterable and how to use them?

An Iterable is a simple representation of a series of elements that can be iterated over. It does not have any iteration state such as a "current element". Instead, it has one method that produces an Iterator.

An Iterator is the object with iteration state. It lets you check if it has more elements using hasNext() and move to the next element (if any) using next().

Typically, an Iterable should be able to produce any number of valid Iterators.

What are iterator, iterable, and iteration?

Iteration is a general term for taking each item of something, one after another. Any time you use a loop, explicit or implicit, to go over a group of items, that is iteration.

In Python, iterable and iterator have specific meanings.

An iterable is an object that has an __iter__ method which returns an iterator, or which defines a __getitem__ method that can take sequential indexes starting from zero (and raises an IndexError when the indexes are no longer valid). So an iterable is an object that you can get an iterator from.

An iterator is an object with a next (Python 2) or __next__ (Python 3) method.

Whenever you use a for loop, or map, or a list comprehension, etc. in Python, the next method is called automatically to get each item from the iterator, thus going through the process of iteration.

A good place to start learning would be the iterators section of the tutorial and the iterator types section of the standard types page. After you understand the basics, try the iterators section of the Functional Programming HOWTO.

Difference between Iterator and Iterable

From Exploring ES6 by Dr. Axel Rauschmayer:

An iterable is a data structure that wants to make its elements accessible to the public. It does so by implementing a method whose key is Symbol.iterator. That method is a factory for iterators.

An iterator is a pointer for traversing the elements of a data structure (think cursors in databases).

How to tell the difference between an iterator and an iterable?

'iterator' if obj is iter(obj) else 'iterable'

why do we need both iterable and iterator concepts?

Conceptually, the object that implements the "iterator" interface just encapsulates the current state of an iteration operation. Once that iterator has been consumed (it.done === true) it cannot be re-used.

The [Symbol.iterator]() function of an "iterable" object returns a new iterator each time it's invoked.

In that respect, be wary of the OP's function which is potentially flawed since the object created by his createIterable function only allows for a one-off call to its Symbol.iterator function. It would fail if the object returned was passed to more than one for .. of operation. Ideally it should read:

function createIterable(ra) {
return {
[Symbol.iterator]() {
return createIterator(ra);
}
}
}

Iterable and Iterator in java

You are right stating what these interfaces are used for. Indeed Iterable declares that the objects of a class implementing it may be iterated over, by providjng an Iterator specific to these objects. Having them is necessary because how exactly the object should be iterated depends on its internal implementation, and an Iterator is therefore specific to a given "collection" class.

Having said that, it is worth noting that although these interfaces are formally a part of Java Collections framework, they can be applied to other cases. Given an imaginary API to read CSV files for example, one can declare a CsvFile class to implement an Iterable<List<String>> and iterate over lines in a file with a dedicated Iterator<List<String>> which will read lines from the file one-by-one and split them into a List of Strings to return it from next().

Another important purpose of these interfaces is a language feature known as "for each" loop - only objects of a class implementing Iterable can be iterated with it. So, given an example from above about CsvFile API, it will also enable something like:

CsvFile csvFile = new CsvFile(pathToCsvFile);
for (List<String> record : csvFile) {
doSomethingWithIt(record);
}

As "for each" loop is purely a language feature, compiler will expand it to use an Iterator as usual.

P.S. Just because it hurts my eyes, I'd like to add that in the example above I would also suggest implementing an AutoCloseable for the CsvFile and using it with try-with-resources.

Iterator vs Iterable?

An iterator is an iterable, but an iterable is not necessarily an iterator.

An iterable is anything that has an __iter__ method defined - e.g. lists and tuples, as well as iterators.

Iterators are a subset of iterables whose values cannot all be accessed at the same time, as they are not all stored in memory at once. These can be generated using functions like map, filter and iter, as well as functions using yield.

In your example, map returns an iterator, which is also an iterable, which is why both functions work with it. However, if we take a list for instance:

>>> lst = [1, 2, 3]
>>> list(lst)
[1, 2, 3]
>>> next(lst)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
next(lst)
TypeError: 'list' object is not an iterator

we can see that next complains, because the list, an iterable, is not an iterator.

Why is Java's Iterator not an Iterable?

Because an iterator generally points to a single instance in a collection. Iterable implies that one may obtain an iterator from an object to traverse over its elements - and there's no need to iterate over a single instance, which is what an iterator represents.



Related Topics



Leave a reply



Submit