Iterators Use Lazy Evaluation

Learn how and when the use of lazy evaluation by iterators is beneficial.

We'll cover the following

Lazy evaluation

The only way to get values from an iterator is to request the next item. This means that if you want to get the 100th100^{th} element, you will have to ask for the next item 100 times! There is no other option.

This means that an iterator doesn’t have to create all its values in one go. In fact, many iterators calculate their values one at a time, as they are needed. Each time you request the next item, the iterator will calculate it there and then. This is called lazy evaluation – the iterator doesn’t do any work until it absolutely has to. There are several advantages to this:

  • When you request the first value, the iterator can return it straight away. Without lazy evaluation, the iterator would need to calculate all the values before it could even return the first value. This can make your program more responsive if the series is very long.
  • You do not need to store the calculated values. A long series might use a lot of memory if you need to store it.
  • You don’t waste time calculating values that you might not use.

To give an example, suppose you had an iterator, myiter, that created 1,000 values, and you wanted to find the first zero value. You could do it like this:

Get hands-on with 1200+ tech skills courses.