Iterators and Generators
Understand iterables, iterators, iter(), next(), StopIteration, yield, and lazy evaluation through practical examples and guided practice.
In this lesson, you will learn
- ✓Distinguish between an iterable, an iterator, and a generator.
- ✓Explain how iter() and next() work and when StopIteration occurs.
- ✓Create and trace generator functions using yield.
- ✓Explain lazy evaluation and how generators can reduce memory usage.
- ✓Use generators with loops, comprehensions, and built-in functions.
- ✓Recognize common iterator mistakes and handle empty or exhausted iterators correctly.
1. Understanding iterables and iterators
An iterable is an object from which Python can obtain an iterator. Lists, tuples, strings, dictionaries, sets, and ranges are common examples of iterables.
An iterator is an object that produces values one at a time. It remembers its current position, so the next request normally produces the next value rather than starting over.
A for loop uses this iteration mechanism behind the scenes. It obtains an iterator, requests values one by one, and stops when the iterator is exhausted.
An iterable and an iterator are not the same thing. A list is reusable and can provide a fresh iterator. A list iterator is consumed as values are requested.
An iterable and its iterator
numbers is a list, so it is iterable. iter(numbers) obtains an iterator over the list. Each next(iterator) requests the next available value. After the third call, all three values have been consumed.
Note
2. How iter() and next() work
The built-in iter() function obtains an iterator from an iterable. The built-in next() function asks an iterator for its next value.
A normal for loop performs these operations automatically. Understanding them explicitly helps you understand how Python processes sequences and why an iterator can become exhausted.
A list can normally be iterated over repeatedly because each call to iter(list) produces a new iterator. Reusing the same iterator does not reset its position.
Requesting values one at a time
The first call returns 4 and advances the original iterator. The second call returns 8 from that same iterator. The new iterator starts at the beginning of the list, so its first value is 4. Creating a new iterator does not reset the old iterator; it creates a separate iterator.
Note
3. Iterator exhaustion and StopIteration
An iterator is exhausted when it has no more values to provide. Calling next() on an exhausted iterator raises StopIteration.
This exception is a normal part of Python's iterator protocol. A for loop handles it internally, which is why a loop finishes without displaying a traceback.
If you want a fallback value instead of an exception, pass a second argument to next(). Python returns that default when the iterator is exhausted.
What happens after the last value?
The first next() returns 7. The second next() returns 9. There are no remaining values, so the third call returns the supplied default, Finished. Because a default was supplied, that final call does not raise StopIteration.
Caution
4. What is a generator?
A generator is a convenient way to create an iterator. Instead of building and returning an entire collection, a generator can produce each value when it is requested.
A generator function looks like a normal function but contains the yield keyword. Calling a generator function creates a generator object; the function body does not run through all its statements immediately.
When next() requests a value, the generator executes until it reaches yield. It produces that value and suspends execution. Its local variables and execution position are preserved so it can continue later.
When the generator reaches the end of its function body, it becomes exhausted. Further requests raise StopIteration.
Your first generator
The function starts number at 1 when iteration begins. Each yield number produces the current number and suspends the generator. When iteration resumes, number += 1 executes. The loop continues while number <= limit. list() consumes the generator and collects its yielded values into a list. For limit=3, the collected values are 1, 2, and 3.
Note
5. Following a generator step by step
The easiest way to understand yield is to track where execution pauses and resumes. A generator does not restart from the beginning after every yield.
After producing a value, it remembers its local variables and continues from the statement immediately following that yield the next time a value is requested.
Trace each yield
Creating generator does not print anything. The first next() executes print("A"), then yields 10. print(next(generator)) prints the yielded value 10. The second next() resumes after the first yield, prints B, and yields 20. The outer print displays 20. C is not printed because the generator has not been resumed after the second yield.
Note
6. yield versus return
Both yield and return can appear in a generator function, but they serve different purposes.
yield produces a value and suspends execution so that iteration can continue later. return ends the generator. A value supplied to return becomes the generator's termination value; it is not automatically yielded as another item.
In ordinary non-generator functions, return sends a result back to the caller and ends the function. In a function containing yield, calling the function creates a generator object instead.
yield produces multiple values
Each yield produces one item. The generator can suspend and resume between items. list() collects all three yielded values.
Caution
7. Lazy evaluation and memory efficiency
Lazy evaluation means that values are produced when needed rather than all being computed or stored in advance.
A list comprehension normally constructs a list containing all its results. A generator expression instead produces a generator that can provide those results one at a time.
Generators can reduce memory usage when processing large sequences because they do not need to store every result simultaneously. They are especially useful for streams, large files, and calculations where only one value at a time is needed.
Generators are not automatically faster in every situation. If you need repeated indexing, reuse of all results, or a small collection that must be accessed many times, a list may be more appropriate.
List comprehension versus generator expression
The list comprehension creates a list containing all five squares. The generator expression creates a generator object rather than a list of all five results. The first next() requests 0. The second next() requests 1. The remaining values are not requested by this example.
Note
8. Generator expressions and built-in functions
A generator expression resembles a list comprehension but uses parentheses instead of square brackets. It is useful when you want to compute values lazily without defining a separate generator function.
Many Python built-ins accept iterables, including sum(), min(), max(), any(), and all(). These functions can consume a generator directly.
Remember that consuming a generator advances it. Once a generator has been exhausted, trying to use it again will not recreate its values.
Use a generator expression with sum()
range(1, 5) produces 1, 2, 3, and 4. The generator expression computes their squares: 1, 4, 9, and 16. sum() consumes those values and adds them. The result is 1 + 4 + 9 + 16 = 30. The parentheses around the generator expression are sufficient as the argument to sum().
Caution
9. Common mistakes and edge cases
Generators are straightforward once you understand that they pause and resume. Many beginner mistakes come from assuming that a generator behaves exactly like a list.
Check what happens when a generator is empty, when it has been fully consumed, and when a loop requests the next value. These cases help you avoid incorrect assumptions.
A generator with no yielded values
The function contains yield, so calling it creates a generator. The condition is false, so the yield statement is never reached. The generator produces no values, and list() returns an empty list.
Note
10. When should you use a generator?
Use a generator when values can be calculated or retrieved one at a time, especially if the complete sequence is large or may not need to be consumed in full.
A generator is useful for reading a large file line by line, producing a numeric sequence, transforming records, or processing data through a pipeline.
Prefer a list when you need indexing, repeated traversal without rebuilding the data, or immediate access to all results. The goal is not to replace every list with a generator; it is to choose the representation that fits the problem.
A simple data-processing pipeline
positive_numbers() examines each input number. It yields only values greater than zero: 4 and 7. sum() consumes the yielded values without requiring a separate list. The final result is 4 + 7 = 11.
Note
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Assuming that calling a generator function immediately runs its body.
Why it happens: Calling a generator function creates a generator object; its body starts running when iteration requests the next value.
Key takeaway: Calling the function creates a generator object. Its body starts executing when iteration requests a value.
#2 Assuming that yield ends the function permanently.
Why it happens: yield suspends a generator and preserves its state so execution can resume on the next request.
Key takeaway: yield pauses the generator. A later next() resumes execution after that yield.
#3 Calling next() on an exhausted iterator without handling exhaustion.
Why it happens: An exhausted iterator raises StopIteration when next() is called again; handle exhaustion or use a for loop.
Key takeaway: Use a for loop, catch StopIteration when manually controlling iteration, or pass a default value to next().
#4 Expecting a generator to restart after it has been consumed.
Why it happens: Generators are single-pass iterators; create a new generator object by calling the generator function again to restart.
Key takeaway: Create a new generator object or materialize the results into a collection when repeated access is required.
#5 Using a list when only one result at a time is needed from a very large sequence.
Why it happens: Building a large list stores every item in memory, while a generator can produce one item at a time as needed.
Key takeaway: Consider a generator or generator expression when lazy processing suits the task.
#6 Expecting return in a generator to produce another iterable item.
Why it happens: return ends the generator; its return value signals completion rather than becoming another yielded item.
Key takeaway: return terminates the generator. Use yield to produce items.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is the difference between an iterable and an iterator?
Q2:What do iter() and next() do?
Q3:What is a generator, and how does yield work?
Q4:What is the difference between yield and return?
Q5:What is lazy evaluation, and why are generators useful?
Q6:Can you iterate over the same generator twice?
Q7:Why does a for loop not normally show StopIteration?
Q8:When would you choose a list instead of a generator?
Key takeaways
- An iterable can provide an iterator; an iterator produces values one at a time.
- iter() obtains an iterator, and next() requests its next value.
- An exhausted iterator raises StopIteration when next() is called without a default.
- A generator function uses yield to produce values and suspend execution.
- Calling a generator function creates a generator object; its body runs as values are requested.
- Generators can reduce memory usage by producing values lazily.
- Generator objects are generally consumed once; create a new generator when you need to iterate again.
- Choose between a list and a generator based on the need for storage, indexing, reuse, and lazy processing.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: