What is the difference between an Iterator and a Generator?
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.
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.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With