Python – Collections Module

Created with Sketch.

Python – Collections Module

The collections module provides alternatives to built-in container data types such as list, tuple and dict.


The namedtuple() function returns a tuple-like object with named fields. These field attributes are accessible by lookup as well as by index.

General usage of this function is:

collections.namedtuple(type_name, field-list)


The following statement declares a student class having name, age and marks as fields.

>>> import collections
>>> student=collections.namedtuple(‘student’, [name, age, marks])

To create a new object of this namedtuple, do the following:

>>> s1=student(“Imran”, 21, 98)

The values of the field can be accessible by attribute lookup:


Or by index:



The OrderedDict() function is similar to a normal dictionary object in Python. However, it remembers the order of the keys in which they were first inserted.

import collections

for k,v in d1.items():
    print (k,v)


A 65
C 67
B 66
D 68


Upon traversing the dictionary, pairs will appear in the order of their insertion.


A deque object support appends and pops from either ends of a list. It is more memory efficient than a normal list object. In a normal list object, the removal of any item causes all items to the right to be shifted towards left by one index.
Hence, it is very slow.

>>> q=collections.deque([10,20,30,40])
>>>qdeque([0, 10, 20, 30, 40])
>>>qdeque([0, 10, 20, 30, 40, 50])
>>>qdeque([0, 10, 20, 30, 40])
>>>qdeque([10, 20, 30, 40])


Learn more about the collections module in Python docs.

Leave a Reply

Your email address will not be published. Required fields are marked *