Python Iterables & IteratorsGet Certified
What Is an Iterable?
An iterable is any object that can be looped over with a for loop, such as a list, tuple, string, dictionary, set, or range() object. An iterable provides a way to obtain an iterator, which is responsible for delivering its values in sequence. This separation lets Python use the same looping pattern with many different kinds of collections. Understanding the distinction is useful when you need to decide whether an object can be restarted or whether it represents a one-pass sequence.
An iterator is the object that actually produces the next value each time you ask for it. You can create an iterator yourself with the built-in iter() function and pull values one by one with next().
- Iterable: an object that can return an iterator (it implements
__iter__()). - Iterator: an object that produces values one at a time (it implements
__next__()). - for loops: automatically create an iterator and keep calling
next()until the iterator is exhausted. - One-time use: most iterators can be used only once. After they are exhausted you must create a new one.
- Memory friendly: iterators do not need to hold every value in memory at the same time.
Seeing the Iterator Behind a for Loop
A for loop handles iteration automatically, but the process becomes clearer when you perform each step yourself. Python obtains an iterator from the iterable and requests one value at a time until no values remain. Calling iter() and next() directly lets you inspect that sequence and control exactly when the next item is requested. This is especially helpful when debugging code that consumes data gradually.
Try It: Manual Iteration over City Names
Click Test My Code. Then try calling next() one more time after the list is finished to see the StopIteration error.
next().cities = ["Chicago", "Austin", "Denver", "Seattle"]
city_iter = iter(cities)
print(next(city_iter))
print(next(city_iter))
print(next(city_iter))
print(next(city_iter))iter() asks the list for an iterator object and stores it in city_iter.next() returns the first city and advances the iterator.next() again would raise StopIteration.Iterators Are Exhausted After One Pass
An iterator keeps track of its current position, so each value is normally returned only once. When it reaches the end, it signals completion with StopIteration and does not restart automatically. The original iterable, such as a list, remains available and can provide a fresh iterator whenever another pass is needed. Keep this behavior in mind when reusing iterators in separate loops or functions.
Try It: One Pass Only
Click Test My Code. Notice that the second loop prints nothing.
students = ["Liam", "Olivia", "Noah", "Emma"]
student_iter = iter(students)
print("First pass:")
for name in student_iter:
print(name)
print("Second pass:")
for name in student_iter:
print(name)
print("Done")Strings, Ranges, and Other Iterables
Python supports iteration across many built-in types, not just lists and tuples. Strings provide characters in order, range objects provide a sequence of integers, and dictionaries provide keys unless you request their values or key-value pairs. These objects can all be used directly in a for loop or passed to iter(). Recognizing these common iterables makes it easier to write flexible code without converting every object into a list.
Try It: Different Kinds of Iterables
Click Test My Code. Then try iterating over a dictionary’s values or items.
next() or a for loop.motto = "USA"
letter_iter = iter(motto)
print(next(letter_iter))
print(next(letter_iter))
print(next(letter_iter))
for n in range(3):
print(n)
capitals = {"Texas": "Austin", "Ohio": "Columbus"}
for state in capitals:
print(state)Creating Multiple Independent Iterators
A reusable iterable can create more than one iterator, and each iterator maintains its own position. Advancing one iterator does not move the other, even when both were created from the same source list. This is useful when two parts of a program need to read the same sequence independently. Remember that this behavior depends on the source being a reusable iterable; an iterator itself is generally a one-pass object.
Try It: Two Iterators on the Same List
Click Test My Code. Watch how the two iterators advance independently.
scores = [88, 92, 75, 96]
iter_a = iter(scores)
iter_b = iter(scores)
print(next(iter_a))
print(next(iter_a))
print(next(iter_b))
print(next(iter_a))
print(next(iter_b))enumerate() and zip() Are Iterators
Python provides enumerate() and zip() to make common iteration tasks easier without building extra lists. enumerate() yields an index together with each item, while zip() yields tuples containing corresponding items from multiple iterables. Because both produce values as they are requested, they can be efficient for large sequences. Their results are iterators, so converting them to a list consumes the remaining values.
Try It: Numbered Roster and Paired Lists
Click Test My Code. Then try converting the zip object to a list to see all pairs at once.
enumerate() and pairs player names with their jersey numbers using zip().players = ["Ava", "Liam", "Mia", "Noah"]
for index, name in enumerate(players, start=1):
print(index, name)
numbers = [10, 23, 7, 14]
paired = zip(players, numbers)
print(next(paired))
print(next(paired))
print(list(paired))Checking Whether Something Is Iterable
Before attempting to loop over an unfamiliar object, you may need to check whether it supports iteration. The collections.abc.Iterable class provides a clear way to test this capability with isinstance(). You can also try calling iter(), although that approach may raise a TypeError for objects that cannot be iterated. This check is useful when writing functions that accept different kinds of input.
Try It: Test Several Objects
Click Test My Code. Then add a few more objects such as a set or a number.
from collections.abc import Iterable
print(isinstance([1, 2, 3], Iterable))
print(isinstance("hello", Iterable))
print(isinstance(42, Iterable))
print(isinstance(range(5), Iterable))
print(hasattr([1, 2], "__iter__"))A Simple Custom Iterator
A custom iterator lets a class decide how values are produced and when iteration should finish. The __iter__() method returns the iterator object, while __next__() supplies the next value each time it is requested. When there are no more values, __next__() must raise StopIteration so that a for loop can stop normally. This pattern is useful for sequences whose values are calculated as the program moves through them.
Try It: Countdown Iterator
Click Test My Code. Then change the starting number to see a longer or shorter countdown.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current < 1:
raise StopIteration
value = self.current
self.current -= 1
return value
for n in Countdown(5):
print(n)Practical Example: Processing a Stream of Scores
Processing values one at a time is useful when data arrives gradually or when holding an entire collection in memory is unnecessary. An iterator can supply each score as the program needs it, allowing calculations such as totals or averages to be updated along the way. The example below uses a running total to show how each new value contributes to the result. The same approach can be adapted to measurements, transaction records, or other sequential data.
Try It: Running Total of Game Scores
Click Test My Code. Then add more scores and watch the running total update.
scores = [14, 21, 9, 28, 17]
score_iter = iter(scores)
total = 0
print("Running total:")
while True:
try:
points = next(score_iter)
total += points
print(total)
except StopIteration:
break
print("Final total:", total)Tip: Prefer a normalforloop whenever you simply need to walk through every item. Reach foriter()andnext()only when you need finer control, such as processing two iterators in parallel or stopping early under complex conditions.
Common Mistakes with Iterables & Iterators
Iteration errors often happen when code treats an iterable and an iterator as if they behave identically. A list can provide a new iterator, but an exhausted iterator does not automatically return to its first item. It is also important to handle the end of manual iteration and avoid changing a collection while looping over it. Reviewing these common cases can prevent missing values, unexpected empty loops, and loops that never finish.
- Re-using an exhausted iterator: After a for loop (or several next() calls) finishes, the iterator is spent. Create a new one with iter() if you need to walk the data again.
- Calling next() without a default: next(iterator) raises StopIteration when finished. Supply a second argument, next(iterator, None), if you want a quiet default value instead.
- Assuming every iterable is an iterator: A list is iterable but not an iterator. You must call iter(list) to obtain an iterator.
- Forgetting StopIteration in a custom iterator: If __next__ never raises StopIteration, a for loop will run forever.
- Modifying a list while iterating over it: Changing the size of a list during a for loop can skip items or raise an error. Prefer iterating over a copy or building a new list.
- Expecting zip to be a list: zip returns an iterator. Convert it with list(zip(…)) only when you need random access or multiple passes.
Good Habits for Working with Iterators
Choose the simplest iteration technique that clearly expresses what your code needs to do. A normal for loop is usually best for processing every item, while explicit calls to iter() and next() are helpful when you need precise control. Use tools such as enumerate() and zip() to keep loops readable and avoid unnecessary indexing. For custom iterators, make the stopping condition clear and ensure that the end of the sequence is signaled correctly.
- Use a plain for loop when you simply need every item; it is clearer and safer.
- Create a fresh iterator with iter() whenever you need a second independent pass.
- Prefer enumerate() over manual index counters.
- Use zip() to walk two or more sequences in parallel instead of indexing by hand.
- When writing a custom iterator, always raise StopIteration to signal the end.
- Remember that most iterators are lazy: they compute the next value only when you ask for it.
Key Takeaways
The central idea is that an iterable provides access to an iterator, and the iterator supplies values one at a time. Python’s for loop performs this process for you, while iter() and next() expose the steps when manual control is needed. Built-in tools such as enumerate() and zip() make everyday iteration more expressive. These concepts form the foundation for understanding generators and other ways of processing data lazily.
- An iterable can be passed to iter() to obtain an iterator.
- An iterator produces values one at a time with next() and raises StopIteration when finished.
- for loops automatically create an iterator and keep calling next() for you.
- Most iterators can be used only once; create a new one for another pass.
- enumerate() and zip() return iterators that pair indexes or values lazily.
- Any class that implements __iter__ and __next__ can act as a custom iterator.
- Prefer for loops for everyday work; reach for explicit iterators when you need finer control.
Frequently Asked Questions
The questions below revisit the main ideas from this lesson and clarify how Python handles iteration in everyday programs. Use them to check the difference between an iterable and an iterator, understand why an iterator becomes exhausted, and review how common built-in tools behave. The answers also cover when a custom iterator may be useful. If a point is still unclear, revisit the matching example and run it with your own values.
What is the difference between an iterable and an iterator?
An iterable is any object that can return an iterator (it has an __iter__ method). An iterator is the object that actually produces the next value (it has a __next__ method). Lists, strings and ranges are iterables; the objects returned by iter() are iterators.
Why does a second for loop over the same iterator print nothing?
Most iterators are exhausted after one complete pass. Once StopIteration has been raised, further calls to next() produce no more values. Create a fresh iterator with iter() if you need another pass.
How does a for loop work internally?
Python calls iter() on the object you give it, then repeatedly calls next() on the resulting iterator until StopIteration is raised. The loop variable receives each value in turn.
Can I turn an iterator back into a list?
Yes. list(my_iterator) consumes the iterator and builds a new list that contains every remaining value. After that call the original iterator is exhausted.
What does next(iterator, default) do?
If the iterator still has values, the next value is returned. If the iterator is exhausted, the default value is returned instead of raising StopIteration. This is useful when you want to handle the end of the sequence quietly.
Are dictionaries iterable?
Yes. A for loop over a dictionary yields its keys. You can also iterate over dict.values() or dict.items() to walk the values or the key-value pairs.
When should I write my own iterator class?
Write a custom iterator when the built-in types are not enough— for example, when you need to generate an infinite sequence, pull data from a network stream, or implement a special traversal order. For simple cases a generator function is usually easier.
Is range an iterator?
No. range is an iterable. Each time you call iter(range(…)) you receive a new independent iterator. That is why you can loop over the same range object many times.