Skip to content
PythonComprehensions and Functional Patternsbeginner30 min read

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

An iterable and its iterator
python
numbers = [10, 20, 30]
iterator = iter(numbers)
 
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output
10 20 30

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

Important distinction: iterable describes an object that can provide an iterator; iterator describes an object that supplies values on successive requests.

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

Requesting values one at a time
python
numbers = [4, 8, 12]
iterator = iter(numbers)
 
print(next(iterator))
print(next(iterator))
 
new_iterator = iter(numbers)
print(next(new_iterator))
Output
4 8 4

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

You do not need to call iter() and next() manually in ordinary loops. These functions are useful when you want to understand or control iteration explicitly.

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?

What happens after the last value?
python
numbers = [7, 9]
iterator = iter(numbers)
 
print(next(iterator))
print(next(iterator))
print(next(iterator, "Finished"))
Output
7 9 Finished

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

Without a default argument, calling next() on an exhausted iterator raises StopIteration. Do not confuse this normal iterator signal with an unexpected programming error.

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

Your first generator
python
def count_up_to(limit):
number = 1
while number <= limit:
yield number
number += 1
 
print(list(count_up_to(3)))
Output
[1, 2, 3]

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

A function containing yield produces a generator iterator when called. A return value from a generator does not behave like another yielded item.

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

Trace each yield
python
def values():
print("A")
yield 10
print("B")
yield 20
print("C")
 
generator = values()
print(next(generator))
print(next(generator))
Output
A 10 B 20

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

When tracing a generator, always distinguish between the generator's internal print statements and the value returned by next().

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

yield produces multiple values
python
def numbers():
yield 1
yield 2
yield 3
 
print(list(numbers()))
Output
[1, 2, 3]

Each yield produces one item. The generator can suspend and resume between items. list() collects all three yielded values.

Caution

Use yield when you want to produce an item for iteration. Use return when you want to finish the generator.

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

List comprehension versus generator expression
python
squares_list = [number * number for number in range(5)]
squares_generator = (number * number for number in range(5))
 
print(squares_list)
print(next(squares_generator))
print(next(squares_generator))
Output
[0, 1, 4, 9, 16] 0 1

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

A generator saves memory by avoiding storage of the entire result sequence. It still needs memory for its generator state and any objects retained by the function.

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()

Use a generator expression with sum()
python
total = sum(number * number for number in range(1, 5))
print(total)
Output
30

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

A generator is usually a one-pass iterator, not a reusable collection. If you need the values multiple times, store them in a list or create a fresh generator.

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

A generator with no yielded values
python
def empty_generator():
if False:
yield 1
 
print(list(empty_generator()))
Output
[]

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

A good debugging habit is to trace each next() request, identify the current suspension point, and check whether the iterator still has values.

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

A simple data-processing pipeline
python
def positive_numbers(numbers):
for number in numbers:
if number > 0:
yield number
 
values = [-3, 0, 4, -1, 7]
result = sum(positive_numbers(values))
print(result)
Output
11

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

Generators can be combined with other iterables and built-in functions to create readable, memory-conscious processing pipelines.

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.

Incorrect Approach
script.py
python
Assuming that calling a generator function immediately runs its body.
Correct Solution
script.py
python
Calling the function creates a generator object. Its body starts executing when iteration requests a 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.

Incorrect Approach
script.py
python
Assuming that yield ends the function permanently.
Correct Solution
script.py
python
yield pauses the generator. A later next() resumes execution after that yield.

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.

Incorrect Approach
script.py
python
Calling next() on an exhausted iterator without handling exhaustion.
Correct Solution
script.py
python
Use a for loop, catch StopIteration when manually controlling iteration, or pass a default value to next().

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.

Incorrect Approach
script.py
python
Expecting a generator to restart after it has been consumed.
Correct Solution
script.py
python
Create a new generator object or materialize the results into a collection when repeated access is required.

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.

Incorrect Approach
script.py
python
Using a list when only one result at a time is needed from a very large sequence.
Correct Solution
script.py
python
Consider a generator or generator expression when lazy processing suits the task.

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.

Incorrect Approach
script.py
python
Expecting return in a generator to produce another iterable item.
Correct Solution
script.py
python
return terminates the generator. Use yield to produce items.

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.

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?
Answer:
An iterable is an object from which Python can obtain an iterator, such as a list or string. An iterator produces values one at a time and maintains its current position. For example, iter([1, 2, 3]) creates an iterator over a list.
Q2:What do iter() and next() do?
Answer:
iter() obtains an iterator from an iterable. next() requests the next value from an iterator. If the iterator is exhausted, next() raises StopIteration unless a default value was supplied.
Q3:What is a generator, and how does yield work?
Answer:
A generator is an iterator commonly created by a function containing yield or by a generator expression. yield produces a value and suspends execution. When another value is requested, execution resumes after the previous yield.
Q4:What is the difference between yield and return?
Answer:
yield produces an item and pauses the generator so it can continue later. return terminates the generator. A value provided to return is not automatically yielded as another item.
Q5:What is lazy evaluation, and why are generators useful?
Answer:
Lazy evaluation produces values when they are requested rather than computing and storing every result in advance. Generators can reduce memory use when processing large sequences, streams, or data that can be handled one value at a time.
Q6:Can you iterate over the same generator twice?
Answer:
A generator object is normally a one-pass iterator. Once exhausted, it does not restart automatically. To process the sequence again, create a new generator or store the values in a reusable collection such as a list.
Q7:Why does a for loop not normally show StopIteration?
Answer:
The for loop handles iterator exhaustion internally. It requests values until the iterator signals that no more values are available, then ends the loop normally.
Q8:When would you choose a list instead of a generator?
Answer:
A list is often preferable when all results are small enough to store comfortably, when repeated traversal is needed, or when indexing and immediate access to elements are important. A generator is useful when values can be processed lazily.

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.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: