[Python-ideas] Implement `itertools.permutations.__getitem__` and `itertools.permutations.index`
Steven D'Aprano
steve at pearwood.info
Mon May 5 19:23:14 CEST 2014
On Mon, May 05, 2014 at 09:07:27AM -0700, Ram Rachum wrote:
> And now that I think about it, I'd also like to give it a `__len__`, and to
> give `itertools.product` the same treatment. What do you think?
Consider:
p = itertools.permutations('CAT')
assert len(p) == 6
So far, that's obvious. But:
next(p)
=> returns a permutation
Now what will len(p) return? If it still returns 6, that will lead to
bugs when people check the len, but fail to realise that some of those
permutations have already been consumed. In the most extreme case, you
could have:
assert len(p) == 6
list(p) == []
which is terribly surprising.
On the other hand, if len(p) returns the number of permutations
remaining, apart from increasing the complexity of the iterator, it will
also be surprising to those who expect the length to be the total number
of permutations.
I would rather have a separate API, perhaps something like this:
p.number() # returns the total number of permutations
--
Steven
More information about the Python-ideas
mailing list