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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Many iterables are defined by generator expressions which don’t have a well defined len. Take the following which iterates forever:
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 (frequentlylistandtuplework just fine) — or you may be able to perform your operation without needing callinglen.