Iteration, Iterable and Iterator Explained in JavaScript and Python

Why Necessary?

One question I always ask myself is why? When there is already array/list and loop, why are iteration, iterator and iterable necessary?

The answer is because of the following facts:

What Are They?

JavaScript

Iterator vs Iterable

Operations on iterable or iterator:

Iteration protocols in JavaScript:

Python

Operations on iterable or iterator:

Iteration in Python

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.
-- https://wiki.python.org/moin/Iterator, modified by Johann considering 2to3

Examples

JavaScript

var oneObject = { 
  name: 'Johann',
  age: 27,
  [Symbol.iterator]: function* () {
    for(const i in this) {
      if (this.hasOwnProperty(i)) {
        yield {[i]: this[i]}
      }
    }
  }
}
for (const property of oneObject) console.log(property)
// {name: "Johann"}
// {age: 27}

var iteratorOfOneObject = oneObject[Symbol.iterator]()
console.log(iteratorOfOneObject.next())
console.log(iteratorOfOneObject.next())
console.log(iteratorOfOneObject.next())
// {value: {name: "Johann"}, done: false}
// {value: {age: 27}, done: false}
// {value: undefined, done: true}
var oneBothIteratorAndIterable = {
  next: function() {
    return {done: true, value: undefined}
  },
  [Symbol.iterator]: function() { return this }
} // an object implemented both iterable and iterator protocols

Python

class OneBothIteratorAndIterable:
  def __init__(self):
    self.keys = iter(range(10))

  def __iter__(self):
    return self.values

  def __next__(self):
    return next(self.keys)

  @property
  def values(self):
    for i in range(10):
      yield i ** 2

oneBothIteratorAndIterable = OneBothIteratorAndIterable()
def generator_func():
  for i in range(10):
    yield i ** 2
iterator_from_generator_func = generator_func()

iterator_from_generator_expr = (i ** 2 for i in range(10))

References


* cached version, generated at 2020-05-17 21:51:49 UTC.

Subscribe by RSS