Get the length of an Iterator in Python

avatar

Borislav Hadzhiev

Last updated: Jun 14, 2022

banner

Photo from Unsplash

Get the length of an Iterator in Python #

To get the length of an iterator in Python:

  1. Use the list() class to convert the iterator to a list.
  2. Pass the list to the len() function, e.g. len(list(gen)).
  3. Note that once the iterator is converted to a list, it is exhausted.
main.py
my_iterator = iter([1, 2, 3, 4, 5]) result = len(list(my_iterator)) print(result) # 👉️ 5

Note that once the iterator is converted to a list it is exhausted.

main.py
my_iterator = iter([1, 2, 3, 4, 5]) print(len(list(my_iterator))) # 👉️ 5 print(len(list(my_iterator))) # 👉️ 0

You can convert the iterator to a list and store the result in a variable.

main.py
my_iterator = iter([1, 2, 3, 4, 5]) my_list = list(my_iterator) print(len(my_list)) # 👉️ 5

Now you can iterate over the list as many times as necessary.

An alternative approach is to use the built-in sum() function.

main.py
my_iterator = iter([1, 2, 3, 4, 5]) result = sum(1 for _ in my_iterator) print(result) # 👉️ 5

The sum function takes an iterable, sums its elements from left to right and returns the total.

We effectively replace each item in the iterator with 1 and sum the values.

This solution doesn't require us to convert the iterator to a list and might be less memory consuming.

However, the difference in performance is negligible unless you're dealing with iterators with many millions of elements.

This approach also exhausts the iterator as there is no way to get the length of an iterator without iterating over it.

Make sure you aren't trying to get the length of an infinite iterator, as that operation would never complete.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.