0

I've stumbled upon an interesting case - only thing I am sure about is that I will get an iterable object.

What I really, and only, want to do is to count it.

I've searched if iterable in python implies countable and I found various places claiming so, except the official docs.

So 2 questions arise:

  1. In Python, does iterable => countable (number of items)? Or is it just very common to be so?

  2. Is there a generic pythonic way to get count from an iterable? Which seems to be answered here https://stackoverflow.com/a/3345807/1835470 i.e. not without counting, but author provided a pythonic one-liner:

    sum(1 for _ in iterableObject)
    
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
jave.web
  • 13,880
  • 12
  • 91
  • 125

1 Answers1

0

iterables do not support the len method. To get their length you have to cast them into something that does support it or manually loop through them (and exhaust them in the process) while counting such as in this code snippet you posted.

As a result, the requirement of using an iterable and needing to know its length is somewhat conflicting. Plus as @Veedrac says in the comments, iterables can have infinite length.

To sum up, if you need to know how many items are contained, you need a different data structure.

Ma0
  • 15,057
  • 4
  • 35
  • 65
  • 1
    you mean don't support len() call on them by default right? The structure is however just fine - sometimes there is no need to know the length and sometimes it is (which can happen in regular cases of list - that said, list in particular supports both) – jave.web Apr 16 '20 at 07:18