Counter
collections
import collections
counter = collections.Counter([1, 2, 2, 3, 3, 3]) # Returns counter object
print(counter) # Output: Counter({3: 3, 2: 2, 1: 1})
print(counter[2]) # Output: 2
counter.update([1, 3, 3, 4]) # Updates the counter in place
print(counter) # Output: Counter({3: 5, 1: 2, 2: 2, 4: 1})
# Subtract counts
counter.subtract([1, 3, 4])
print(counter) # Output: Counter({3: 4, 2: 2, 1: 1, 4: 0})
# Get elements
elements = list(counter.elements())
print(elements) # Output: [1, 1, 2, 2, 3, 3, 3, 3]
# Get most common elements
most_common = counter.most_common(2)
print(most_common) # Output: [(3, 4), (2, 2)]
# Arithmetic operations
counter1 = Counter([1, 2, 2, 3])
counter2 = Counter([2, 3, 3, 4])
print(counter1 + counter2) # Output: Counter({3: 3, 2: 3, 1: 1, 4: 1})
print(counter1 - counter2) # Output: Counter({1: 1})
print(counter1 & counter2) # Output: Counter({2: 1, 3: 1})
print(counter1 | counter2) # Output: Counter({3: 2, 2: 2, 1: 1, 4: 1})