List Count

Terry Jan Reedy tjreedy at udel.edu
Tue Apr 23 16:00:56 EDT 2013


On 4/23/2013 12:57 PM, Blind Anagram wrote:

> So, all I was doing in asking for advice was to check whether there is
> an easy way of avoiding the slice copy,

And there is.

> not because this is critical,
> but rather because it is a pity to limit the performance because Python
> forces a (strictly unnecessary) copy in order to perform a count within
> a part of a list.

Python does not force that. You have been given several simple no-copy 
alternatives. They happen to be slower *with CPython* because of the 
speed difference between Python code and C code. If the same timing 
tests were done with any of the implementations that execute python code 
faster, the results would likely be different.

I thing str/byte/bytearray.count have more need for optional start,stop 
boundary parameters because a) people search in long texts and subtexts, 
more so I think that for other sequences, b) they search for substrings 
longer than 1 and hence c) the generic no-slice alternatives do not work 
for counting substrings.

That said, I do see that tuple/list.index have had start, stop 
paramaters added, so doing the same for .count is conceivable. I just do 
not remember anyone else asking for such. The use case must be very 
rare. And as I said in my other post, .count(x) applies to any 
collections, but start,stop would only apply to sequences.

> In other words, the lack of a list.count(value, limit) function makes
> Python less effective than it would otherwise be.

Untrue. The alternatives are just as *effective*.





More information about the Python-list mailing list