Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between an Iterator and a Generator?

What is the difference between an Iterator and a Generator?

like image 411
mudge Avatar asked Jun 20 '09 21:06

mudge


People also ask

What is difference between iterator and generator in Javascript?

An iterator is typically something that has a next method to get the next element from a stream. A generator is an iterator that is tied to a function. This has the advantage that you don't need to store infinite numbers in memory to iterate over them.

Which is faster generator or iterator?

From the timings above you can see that the generator function variant of the self-made range() iterator runs faster than the iterator class variant and when no optimization of code is involved this behavior propagates also into C-code level of C-code created by Cython.

What is difference between iterator and iterable?

An Iterable is basically an object that any user can iterate over. An Iterator is also an object that helps a user in iterating over another object (that is iterable). We can generate an iterator when we pass the object to the iter() method.

Why generators are faster than iterators?

Iterators allow lazy evaluation, only generating the next element of an iterable object when requested. This is useful for very large data sets. Iterators and generators can only be iterated over once. Generator Functions are better than Iterators.


1 Answers

An iterator traverses a collection one at a time.

A generator generates a sequence, one item at a time.

You might for example, iterate over the result of a generator...

like image 51
Nader Shirazie Avatar answered Oct 12 '22 19:10

Nader Shirazie