How do I tell whether a Python value is iterable or an iterator?
Quick answer
An iterable is a value from which iter(value) can produce an iterator. An iterator delivers values one at a time with next() and signals exhaustion with StopIteration. For example, a list is iterable; iter(the_list) gives you an iterator. Each successful call to next() advances that iterator, so it can run out. [S1]
The question, the details, the next step.
A practical checklist
Identify whether you are checking the original value or an iterator you already have.
Use
iter(value)to try to obtain an iterator; handleTypeErrorif appropriate.Call
next(iterator)only when you intend to retrieve a value.Handle
StopIterationwhen an iterator has no more values.Keep a retrieved value if your program still needs to process it.
A few more useful answers
Does calling `iter()` tell me whether an iterator still has values?
No. It tries to obtain an iterator; it does not retrieve the next value. To check for a value, call next() and handle possible exhaustion.
Can I call `next()` on a list directly?
First obtain an iterator with iter(the_list), then call next() on that iterator. The documented example demonstrates successive next() calls on an iterator created from a list. [S1]
Sources
References used for this guide.
- [S1] Functional Programming HOWTO — Python 3.15.2 documentation docs.python.org · Checked
