List Count

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Apr 23 16:38:38 EDT 2013


On 23 April 2013 21:00, Terry Jan Reedy <tjreedy at udel.edu> wrote:
>
> That said, I do see that tuple/list.index have had start, stop paramaters
> added, so doing the same for .count is conceivable.

Are those new? I don't remember them not being there.

You need the start/stop parameters to be able to use index for finding
all occurrences of an item rather than just the first:

def indices(value, sequence):
    i = -1
    while True:
        try:
            i = sequence.index(value, i + 1)
        except ValueError:
            return
        yield i

I thought this was a common use case for .index() and that if the
interface had been designed more recently then it might have just been
an .indices() method that returned an iterator.


Oscar



More information about the Python-list mailing list