Last updated: Apr 8, 2024
Reading timeยท3 min
To get the length of a generator in Python:
list()
class to convert the generator to a list.len()
function, e.g. len(list(gen))
.def g(): yield 1 yield 2 yield 3 gen = g() result = len(list(gen)) print(result) # ๐๏ธ 3
Note that once the generator is converted to a list it is exhausted.
def g(): yield 1 yield 2 yield 3 gen = g() print(len(list(gen))) # ๐๏ธ 3 print(len(list(gen))) # ๐๏ธ 0
You can convert the generator to a list and store the result in a variable.
def g(): yield 1 yield 2 yield 3 gen = g() my_list = list(gen) print(len(my_list)) # ๐๏ธ 3
Now you can iterate over the list as many times as necessary.
An alternative approach is to use the built-in sum()
function.
def g(): yield 1 yield 2 yield 3 gen = g() result = sum(1 for _ in gen) print(result) # ๐๏ธ 3 print(list(gen)) # ๐๏ธ []
The sum() function takes an iterable, sums its items from left to right and returns the total.
We effectively replace each item in the generator with 1
and sum the values.
This solution doesn't require us to convert the generator to a list and might be less memory-consuming.
However, the difference in performance is negligible unless you're dealing with generators with many millions of items.
Make sure you aren't trying to get the length of an infinite generator, as that operation would never be completed.
The same approach can be used to get the length of an iterator.
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.
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.
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.
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.
Make sure you aren't trying to get the length of an infinite iterator, as that operation would never be completed.
You can learn more about the related topics by checking out the following tutorials: