Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does len() not support iterators?

Many of Python's built-in functions (any(), all(), sum() to name some) take iterables but why does len() not?

One could always use sum(1 for i in iterable) as an equivalent, but why is it len() does not take iterables in the first place?

like image 936
iruvar Avatar asked Jul 13 '12 01:07

iruvar


People also ask

What does Len () do in Python?

The function len() is one of Python's built-in functions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types.

Does Len count from 0 Python?

The len() function returns the length of a string, the number of chars in it. It is valid to have a string of zero characters, written just as '' , called the "empty string". The length of the empty string is 0.

What is a lazy iterator?

An LazyIteratorChain is an Iterator that wraps a number of Iterators in a lazy manner. This class makes multiple iterators look like one to the caller.


1 Answers

Many iterables are defined by generator expressions which don't have a well defined len. Take the following which iterates forever:

def sequence(i=0):
    while True:
        i+=1
        yield i

Basically, to have a well defined length, you need to know the entire object up front. Contrast that to a function like sum. You don't need to know the entire object at once to sum it -- Just take one element at a time and add it to what you've already summed.

Be careful with idioms like sum(1 for i in iterable), often it will just exhaust iterable so you can't use it anymore. Or, it could be slow to get the i'th element if there is a lot of computation involved. It might be worth asking yourself why you need to know the length a-priori. This might give you some insight into what type of data-structure to use (frequently list and tuple work just fine) -- or you may be able to perform your operation without needing calling len.

like image 66
mgilson Avatar answered Sep 28 '22 08:09

mgilson