Iterators and yield return

A method with yield return produces its values one at a time, pausing between them until the caller asks for the next.

Time O(1) per itemSpace O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Calling Evens runs none of its code. Each time foreach asks for the next value, the method runs until it reaches yield return, hands over that value, and freezes with all its local variables intact.

Code

static IEnumerable<int> Evens(int max) {
    for (int i = 0; i <= max; i += 2)
        yield return i;   // pause here and hand i to the caller
}

int max = 6;
foreach (int n in Evens(max))
    Console.Write(n);
public class Main {
    static Iterable<Integer> evens(int max) {   // Java has no yield: an Iterator keeps the loop state
        return () -> new Iterator<Integer>() {
            int i = 0;                                       // the loop variable survives between calls
            public boolean hasNext() { return i <= max; }    // false ends the sequence
            public Integer next() { int v = i; i += 2; return v; }   // hand i to the caller
        };
    }

    public static void main(String[] args) {
        int max = 6;
        for (int n : evens(max))
            System.out.print(n);
    }
}
class Evens {   // C++17 has no yield: the generator's state lives in an object
    int i = 0, max;   // the loop variable survives between calls
public:
    Evens(int max) : max(max) {}
    bool next(int& out) {
        if (i > max) return false;   // the sequence is finished
        out = i; i += 2;   // hand i to the caller and remember where we stopped
        return true;
    }
};

void printEvens(int max) {
    Evens gen(max);
    for (int n; gen.next(n); )
        cout << n;
}
def evens(max_value: int):
    for i in range(0, max_value + 1, 2):
        yield i  # pause here and hand i to the caller
    return  # the generator is finished

max_value = 6
for n in evens(max_value):
    print(n, end="")

Tips

In the .NET library

The compiler turns an iterator method into a hidden class that implements IEnumerator<T>, with a state field that remembers where it paused.