Getting number of elements in an iterator in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
An iterator in Python does not generally know its own length. Unlike a list or tuple, it produces values one at a time and may even represent an infinite stream. That is why len(iterator) usually fails.
If you need the number of elements, the core question is whether you are willing to consume the iterator. In most cases, counting an iterator means iterating through it, which leaves it exhausted afterward.
The Direct Counting Pattern
The standard way to count elements in an iterator is:
Example:
This is simple and memory-efficient because it does not store the elements. It only counts them.
The tradeoff is important: after this function runs, it is exhausted.
Why The Iterator Gets Consumed
An iterator is a one-way stream of values. Every call to next advances it. Counting requires reading every remaining item, so there is nothing left afterward.
The second print shows an empty list because the iterator has already been consumed by the count.
When len Still Works
Sometimes people say "iterator" when they really mean an iterable container such as a list, tuple, or range. For those objects, len is the correct tool:
So the first step is to distinguish between:
- an iterable container that can produce a fresh iterator
- an iterator object that is already being consumed
That distinction matters much more than the counting syntax itself.
Converting To A List
Another common pattern is:
This works, but it stores every element in memory. For a small iterator, that is fine. For a large iterator or a stream, it can be wasteful or impossible.
Use this approach only when you also need to keep the elements for later reuse.
If You Need Both Count And Values
If you need to count the elements and still keep them, materializing them once is reasonable:
If you need only the count, prefer the generator-based sum approach because it avoids unnecessary storage.
Sometimes The Right Answer Is len
If the source object is actually a container such as a list, tuple, or range, do not convert it into an iterator just to count it. Call len on the container directly. Counting by consumption is only the right tool when you already have a true iterator or stream and cannot know the size in advance.
Common Pitfalls
- Calling
lenon a true iterator and expecting it to work. - Forgetting that counting consumes the iterator.
- Converting a huge iterator to a list just to get the count.
- Confusing iterables such as lists with iterators created from them.
- Trying to count an infinite iterator, which never finishes.
Summary
- True iterators usually do not know their length ahead of time.
- The common counting pattern is
sum(1 for _ in iterator). - Counting consumes the iterator because every element must be read.
- '
lenworks on containers such as lists, not on most iterator objects.' - Convert to a list only when you need both the count and the stored values.
Related reading
- Getting one value from a tuple
- Getting pika.exceptions.StreamLostError Transport indicated EOF while running python script docker image which using pika
- Getting rid of n when using .readlines
- Getting S3 objects' last modified datetimes with boto
- Getting started with secure AWS CloudFront streaming with Python
- Getting tensorflow is not a supported wheel on this platform
- Getting the class name of an instance
- Getting the docstring from a function
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.