5

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
  • 356
  • 1
  • 9
  • 24
  • Note that you can compute some of those likely faster than just iterating over them - for instance a length of `itertools.permutations` can be computed by importing `math.perm` and using the length of the iterable and the (optional argument) group size passed to `itertools.permutations` without having to iterate over it. Take this for example: `from math import perm; from itertools import permutations as p; letters = "asdfjkl"; group = 3; it = p(letters, group); total = perm(len(letters), group); length = sum(1 for _ in it); length == total;` – Shmack Nov 15 '22 at 21:46

3 Answers3

13

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
  • 67,464
  • 13
  • 126
  • 132
  • 2
    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
3

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
  • 50,847
  • 7
  • 72
  • 76
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
  • 286
  • 2
  • 13