enhancing 'list'

Peter Otten __peter__ at web.de
Mon Jan 18 04:06:42 EST 2010


samwyse wrote:

> Lately, I've slinging around a lot of lists, and there are some simple
> things I'd like to do that just aren't there.
> 
> s.count(x[, cmp[, key]])
> - return number of i‘s for which s[i] == x.  'cmp' specifies a custom
> comparison function of two arguments, as in '.sort'.  'key' specifies
> a custom key extraction function of one argument.

What's your use case exactly? If I were to enhance count/index/rindex I 
would go for the simpler

>>> missing = object()                                                  
>>> class List(list):                                                 
...     def count(self, value=missing, predicate=missing):            
...             if value is missing:
...                     if predicate is missing:
...                             raise TypeError
...                     return sum(1 for item in self if predicate(item))
...             else:
...                     if predicate is not missing:
...                             raise TypeError
...                     return list.count(self, value)
...
>>> items = List(range(10))
>>> items.count(7)
1
>>> items.count(predicate=lambda item: item%3)
6

which nicely covers all applications I can imagine.

Peter



More information about the Python-list mailing list