class - collections

 

 

 


Usage

 

import collections

 

Use set() to remove duplicates if all values are hashable:

>>> your_list = ['one', 'two', 'one']
>>> len(your_list)!=len(set(your_list))

True

x=[1, 2, 3, 5, 6, 7, 5, 2]

y=collections.Counter(x)

>>> y

Counter({2: 2, 5: 2, 1: 1, 3: 1, 6: 1, 7: 1})

>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args
>>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping

>>> c['yellow']                              # count of a missing element is zero

0

>>> c['red'] = 0                        # counter entry with a zero count

>>> del c['red']                        # del actually removes the entry

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())

['a', 'a', 'a', 'a', 'b', 'b']

 

Creative Commons license icon Creative Commons license icon