I have used during a problem this piece of code to retrieve the count of each element in a list :
nums = [1,1,3,2,3,3,4,1,1,4,2,3,3,2,1,3,4,1,2]
print([nums.count(num) for num in set(nums)])
This code works well but doesn't look like to be as efficient as this code :
from collections import Counter
nums = [1,1,3,2,3,3,4,1,1,4,2,3,3,2,1,3,4,1,2]
counter = Counter(nums)
print(counter.values())
Can someone explains to me why is the collections library is more faster than the vanilla list comprehension ?
The code with
Counteris roughly equivalent to:The code with
.countis roughly equivalent to:As you can see, function
counter_v1iterates through the sequence once, with a single for-loop. By contrast, functioncounter_v2iterates through the sequence once per distinct element, with a for-loop inside another for-loop.The runtime of
counter_v1will be roughly proportional tolen(seq), whereas the runtime ofcounter_v2will be roughly proportional tolen(seq) * len(set(seq)), which is usually much bigger.