Is there any built-in way to get the length of an iterable in python?

Short of iterating through the iterable and counting the number of iterations, no. That’s what makes it an iterable and not a list. This isn’t really even a python-specific problem. Look at the classic linked-list data structure. Finding the length is an O(n) operation that involves iterating the whole list to find the number of elements.

As mcrute mentioned above, you can probably reduce your function to:

def count_iterable(i):
    return sum(1 for e in i)

Of course, if you’re defining your own iterable object you can always implement __len__ yourself and keep an element count somewhere.

Leave a Comment