# How To Get The Length Of A Generator In Python

To get the length of a Generator in Python, I will show you some ways like using the more_itertools.ilen() function from the more_itertools package, or using the len() function to get the length. Read the specific article below.

## Get the length of a Generator in Python

The generator is a simple way to create iterators. Without a generator, creating an iterator goes through quite a few steps, such as implementing the class with __iter()__ and __next()__ methods, keeping track of the internal conditions, keeping track of the StopIteration that occurs when no value is returned. Simplified, a Generator is a function that returns an iterator object that we can iterate over.In creating a Generator, you still use the ‘def’ keyword like a function, but instead of ‘return’ as a function, the generator uses the ‘yield’ statement to return the elements.

### Use the more_itertools.ilen() function from the more_itertools package

Syntax:

more_itertools.ilen(iterable)

The more_itertools.ilen() function returns the number of items in iterable.

Example:

• Import the more_itertools module.
• Create a generator.
• Use the more_itertools.ilen() function to get the length of the generator.
import more_itertools

def myGenerator():
yield 'John'
yield 'Frank'
yield 'Peter'

# Use the more_itertools.ilen() function to get the length of the generator
print('Length of generator:', more_itertools.ilen(myGenerator()))

Output:

Length of generator: 3

Note: If you get the ModuleNotFoundError: No module named ‘more_itertools’, then install the more_itertools package as follows: pip install more-itertools.

### Use the len() function

Example:

• Create a generator.
• Use the list() function to convert the generator to a list.
• Use the len() function to get the length of the list or the length of the generator itself.
def myGenerator():
yield 'John'
yield 'Frank'
yield 'Peter'

myGen = myGenerator()

# Use the list() function to convert the generator to a list
convertToList = list(myGen)

# Use the len() function to get the length of the list (the generator converts to a list)
print('Length of generator:', len(convertToList))

Output:

Length of generator: 3

Or you can use a for loop to get the length.

Example:

def myGenerator():
yield 'John'
yield 'Frank'
yield 'Peter'

myGen = myGenerator()

# Use the list() function to convert the generator to a list.
convertToList = list(myGen)

# Use the for loop to get the length of the list or the length of the generator itself.
counter = 0
for item in convertToList:
counter+=1

print('Length of generator:', counter)

Output:

Length of generator: 3

## Summary

Those are the ways to get the length of a Generator in Python. You can take advantage of Python’s convenience by using the built-in more_itertools.ilen() function to do this. If you have any questions about the article, leave a comment below. Thanks!

Maybe you are interested: