Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of python list count method [duplicate]

In python, it's very easy to get the count of a particular item in a list:

>>> L = [1,1,1,2,3,4]
>>> print(L.count(1))
3

Is this method O(N)? Is it advisable to use this method, or are there better ways of quickly getting the count of an arbitrary number of elements in a list (i.e. a way to avoid O(mN), where m is the number of records for which a call to count is required).

like image 691
rookie Avatar asked Jun 11 '26 02:06

rookie


1 Answers

Yes, use collections.Counter if you need to count more than one time through the iterable. Then you will only have to iterate once.

>>> from collections import Counter
>>> counter = Counter('hellooo i am a potato!!!!!')
>>> counter.most_common(2)
[('o', 5), ('!', 5)]
like image 137
wim Avatar answered Jun 12 '26 15:06

wim