3

Is there anyway to see the len() of an itertools.Combination or other object, really, without materializing it to a list?
I can get the cardinality of combs or permutations with the factorials,... but I want something that generalizes.

Thanks

mik
  • 316
  • 8
  • 23

3 Answers3

10

For any iterable it, you can do:

length = sum(1 for ignore in it)

That doesn't create a list, so the memory footprint is small. But for many kinds of iterables, it also consumes it (for example, if it is a generator, it's consumed and can't be restarted; if it is a list, it's not consumed). There is no generally "non-destructive" way to determine the length of an arbitrary iterable.

Also note that the code above will run "forever" if it delivers an unbounded sequence of objects.

Tim Peters
  • 63,230
  • 10
  • 119
  • 128
  • 1
    This modifies an iterator so that attempting to iterate over it again does nothing. To mitigate that where I'm using itertools, I did: `import itertools`, then `itCopy = itertools.tee(it)`, then `length = sum(1 for ignore in itCopy)`, then `for i in list(it): ..` – Alex Hall Mar 16 '20 at 23:39
2

No need to create a list. You can count the number of items in an iterable without storing the entire set:

sum(1 for _ in myIterable)
jspcal
  • 49,231
  • 7
  • 69
  • 74
2

Yes,

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

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

DecaK
  • 266
  • 1
  • 12