In addition to the concrete container classes, the collections module provides
abstract base classes that can be
used to test whether a class provides a particular interface, for example,
whether it is hashable or a mapping.

A Counter is a dict subclass for counting hashable objects.
It is an unordered collection where elements are stored as dictionary keys
and their counts are stored as dictionary values. Counts are allowed to be
any integer value including zero or negative counts. The Counter
class is similar to bags or multisets in other languages.

Elements are counted from an iterable or initialized from another
mapping (or counter):

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

Counter objects have a dictionary interface except that they return a zero
count for missing items instead of raising a KeyError:

>>> c=Counter(['eggs','ham'])>>> c['bacon']# count of a missing element is zero0

Setting a count to zero does not remove an element from a counter.
Use del to remove it entirely:

Return a list of the n most common elements and their counts from the
most common to the least. If n is omitted or None,
most_common() returns all elements in the counter.
Elements with equal counts are ordered arbitrarily:

Elements are counted from an iterable or added-in from another
mapping (or counter). Like dict.update() but adds counts
instead of replacing them. Also, the iterable is expected to be a
sequence of elements, not a sequence of (key,value) pairs.

sum(c.values())# total of all countsc.clear()# reset all countslist(c)# list unique elementsset(c)# convert to a setdict(c)# convert to a regular dictionaryc.items()# convert to a list of (elem, cnt) pairsCounter(dict(list_of_pairs))# convert from a list of (elem, cnt) pairsc.most_common()[:-n-1:-1]# n least common elementsc+=Counter()# remove zero and negative counts

Several mathematical operations are provided for combining Counter
objects to produce multisets (counters that have counts greater than zero).
Addition and subtraction combine counters by adding or subtracting the counts
of corresponding elements. Intersection and union return the minimum and
maximum of corresponding counts. Each operation can accept inputs with signed
counts, but the output will exclude results with counts of zero or less.

Counters were primarily designed to work with positive integers to represent
running counts; however, care was taken to not unnecessarily preclude use
cases needing other types or negative values. To help with those use cases,
this section documents the minimum range and type restrictions.

The Counter class itself is a dictionary subclass with no
restrictions on its keys and values. The values are intended to be numbers
representing counts, but you could store anything in the value field.

The most_common() method requires only that the values be orderable.

For in-place operations such as c[key]+=1, the value type need only
support addition and subtraction. So fractions, floats, and decimals would
work and negative values are supported. The same is also true for
update() and subtract() which allow negative and zero values
for both inputs and outputs.

The multiset methods are designed only for use cases with positive values.
The inputs may be negative or zero, but only outputs with positive values
are created. There are no type restrictions, but the value type needs to
support addition, subtraction, and comparison.

Returns a new deque object initialized left-to-right (using append()) with
data from iterable. If iterable is not specified, the new deque is empty.

Deques are a generalization of stacks and queues (the name is pronounced “deck”
and is short for “double-ended queue”). Deques support thread-safe, memory
efficient appends and pops from either side of the deque with approximately the
same O(1) performance in either direction.

Though list objects support similar operations, they are optimized for
fast fixed-length operations and incur O(n) memory movement costs for
pop(0) and insert(0,v) operations which change both the size and
position of the underlying data representation.

New in version 2.4.

If maxlen is not specified or is None, deques may grow to an
arbitrary length. Otherwise, the deque is bounded to the specified maximum
length. Once a bounded length deque is full, when new items are added, a
corresponding number of items are discarded from the opposite end. Bounded
length deques provide functionality similar to the tail filter in
Unix. They are also useful for tracking transactions and other pools of data
where only the most recent activity is of interest.

In addition to the above, deques support iteration, pickling, len(d),
reversed(d), copy.copy(d), copy.deepcopy(d), membership testing with
the in operator, and subscript references such as d[-1]. Indexed
access is O(1) at both ends but slows to O(n) in the middle. For fast random
access, use lists instead.

The rotate() method provides a way to implement deque slicing and
deletion. For example, a pure Python implementation of deld[n] relies on
the rotate() method to position elements to be popped:

defdelete_nth(d,n):d.rotate(-n)d.popleft()d.rotate(n)

To implement deque slicing, use a similar approach applying
rotate() to bring a target element to the left side of the deque. Remove
old entries with popleft(), add new entries with extend(), and then
reverse the rotation.
With minor variations on that approach, it is easy to implement Forth style
stack manipulations such as dup, drop, swap, over, pick,
rot, and roll.

Returns a new dictionary-like object. defaultdict is a subclass of the
built-in dict class. It overrides one method and adds one writable
instance variable. The remaining functionality is the same as for the
dict class and is not documented here.

The first argument provides the initial value for the default_factory
attribute; it defaults to None. All remaining arguments are treated the same
as if they were passed to the dict constructor, including keyword
arguments.

New in version 2.5.

defaultdict objects support the following method in addition to the
standard dict operations:

When each key is encountered for the first time, it is not already in the
mapping; so an entry is automatically created using the default_factory
function which returns an empty list. The list.append()
operation then attaches the value to the new list. When keys are encountered
again, the look-up proceeds normally (returning the list for that key) and the
list.append() operation adds another value to the list. This technique is
simpler and faster than an equivalent technique using dict.setdefault():

When a letter is first encountered, it is missing from the mapping, so the
default_factory function calls int() to supply a default count of
zero. The increment operation then builds up the count for each letter.

The function int() which always returns zero is just a special case of
constant functions. A faster and more flexible way to create constant functions
is to use itertools.repeat() which can supply any constant value (not just
zero):

Named tuples assign meaning to each position in a tuple and allow for more readable,
self-documenting code. They can be used wherever regular tuples are used, and
they add the ability to access fields by name instead of position index.

Returns a new tuple subclass named typename. The new subclass is used to
create tuple-like objects that have fields accessible by attribute lookup as
well as being indexable and iterable. Instances of the subclass also have a
helpful docstring (with typename and field_names) and a helpful __repr__()
method which lists the tuple contents in a name=value format.

The field_names are a sequence of strings such as ['x','y'].
Alternatively, field_names can be a single string with each fieldname
separated by whitespace and/or commas, for example 'xy' or 'x,y'.

Any valid Python identifier may be used for a fieldname except for names
starting with an underscore. Valid identifiers consist of letters, digits,
and underscores but do not start with a digit or underscore and cannot be
a keyword such as class, for, return, global, pass, print,
or raise.

If rename is true, invalid fieldnames are automatically replaced
with positional names. For example, ['abc','def','ghi','abc'] is
converted to ['abc','_1','ghi','_3'], eliminating the keyword
def and the duplicate fieldname abc.

If verbose is true, the class definition is printed just before being built.

Named tuple instances do not have per-instance dictionaries, so they are
lightweight and require no more memory than regular tuples.

In addition to the methods inherited from tuples, named tuples support
three additional methods and one attribute. To prevent conflicts with
field names, the method and attribute names start with an underscore.

Ordered dictionaries are just like regular dictionaries but they remember the
order that items were inserted. When iterating over an ordered dictionary,
the items are returned in the order their keys were first added.

Return an instance of a dict subclass, supporting the usual dict
methods. An OrderedDict is a dict that remembers the order that keys
were first inserted. If a new entry overwrites an existing entry, the
original insertion position is left unchanged. Deleting an entry and
reinserting it will move it to the end.

The popitem() method for ordered dictionaries returns and removes
a (key, value) pair. The pairs are returned in LIFO order if last is
true or FIFO order if false.

In addition to the usual mapping methods, ordered dictionaries also support
reverse iteration using reversed().

Equality tests between OrderedDict objects are order-sensitive
and are implemented as list(od1.items())==list(od2.items()).
Equality tests between OrderedDict objects and other
Mapping objects are order-insensitive like regular
dictionaries. This allows OrderedDict objects to be substituted
anywhere a regular dictionary is used.

The OrderedDict constructor and update() method both accept
keyword arguments, but their order is lost because Python’s function call
semantics pass-in keyword arguments using a regular unordered dictionary.

The new sorted dictionaries maintain their sort order when entries
are deleted. But when new keys are added, the keys are appended
to the end and the sort is not maintained.

It is also straight-forward to create an ordered dictionary variant
that remembers the order the keys were last inserted.
If a new entry overwrites an existing entry, the
original insertion position is changed and moved to the end:

classLastUpdatedOrderedDict(OrderedDict):'Store items in the order the keys were last added'def__setitem__(self,key,value):ifkeyinself:delself[key]OrderedDict.__setitem__(self,key,value)

An ordered dictionary can be combined with the Counter class
so that the counter remembers the order elements are first encountered:

classOrderedCounter(Counter,OrderedDict):'Counter that remembers the order elements are first encountered'def__repr__(self):return'%s(%r)'%(self.__class__.__name__,OrderedDict(self))def__reduce__(self):returnself.__class__,(OrderedDict(self),)

These ABCs allow us to ask classes or instances if they provide
particular functionality, for example:

size=Noneifisinstance(myvar,collections.Sized):size=len(myvar)

Several of the ABCs are also useful as mixins that make it easier to develop
classes supporting container APIs. For example, to write a class supporting
the full Set API, it only necessary to supply the three underlying
abstract methods: __contains__(), __iter__(), and __len__().
The ABC supplies the remaining methods such as __and__() and
isdisjoint()

classListBasedSet(collections.Set):''' Alternate set implementation favoring space over speed and not requiring the set elements to be hashable. '''def__init__(self,iterable):self.elements=lst=[]forvalueiniterable:ifvaluenotinlst:lst.append(value)def__iter__(self):returniter(self.elements)def__contains__(self,value):returnvalueinself.elementsdef__len__(self):returnlen(self.elements)s1=ListBasedSet('abcdef')s2=ListBasedSet('defghi')overlap=s1&s2# The __and__() method is supported automatically

Since some set operations create new sets, the default mixin methods need
a way to create new instances from an iterable. The class constructor is
assumed to have a signature in the form ClassName(iterable).
That assumption is factored-out to an internal classmethod called
_from_iterable() which calls cls(iterable) to produce a new set.
If the Set mixin is being used in a class with a different
constructor signature, you will need to override _from_iterable()
with a classmethod that can construct new instances from
an iterable argument.

To override the comparisons (presumably for speed, as the
semantics are fixed), redefine __le__() and __ge__(),
then the other operations will automatically follow suit.

The Set mixin provides a _hash() method to compute a hash value
for the set; however, __hash__() is not defined because not all sets
are hashable or immutable. To add set hashability using mixins,
inherit from both Set() and Hashable(), then define
__hash__=Set._hash.