Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Itertools Combinations/Permutations size [duplicate]

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

like image 463
mik Avatar asked Jul 13 '26 01:07

mik


2 Answers

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.

like image 87
Tim Peters Avatar answered Jul 14 '26 16:07

Tim Peters


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)
like image 40
jspcal Avatar answered Jul 14 '26 15:07

jspcal