Collection in Python
Collections in Python are containers used for storing data and are commonly known as data structures, such as lists, tuples, arrays, dictionaries, etc. It was introduced to improve the functionalities of the built-in collection containers.
Python has a built-in collections module providing additional data structures for collections of data.
Most commonly used collection modules are as follows:
- Defaultdict()
- Counter()
- Deque()
- Namedtuple()
- ChainMap
- OrderedDict()
1. Defaultdict(): Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. Defaultdict never raises a KeyError. It provides a default value for the key that does not exist.
syntax:
class collections.defaultDict()Example:
from collections import defaultdict
nums = defaultdict(int)
nums['one'] = 1
nums['two'] = 2
nums['three'] = 3
print(nums['four'])OUTPUT:
0
In the above code, even though the 4th index was not initialized, the compiler still returns a value, 0, when we try to access it.
2. Counter(): Counter is a built-in data structure which is used to count the occurrence of each value present in an array or list.
Syntax:
class collections.Counter()Example:
from collections import Counter
list = [1,2,3,4,1,2,6,7,3,8,1,2,2]
answer = Counter(list)
print(answer[2])OUTPUT:
4
The above code is counting the number of occurrences of the value 2 in the given list.
Get Rai Mohit Samshersingh’s stories in your inbox
Join Medium for free to get updates from this writer.
3. Deque(): The Python deque() is a double-ended queue which allows us to add and remove elements from both the ends. It is an optimal version of list used for inserting and removing items.
Example:
from collections import deque
list = ["a","b","c"]
deq = deque(list)
print(deq)
deq.append("z")
deq.appendleft("g")
print(deq)
deq.pop()
deq.popleft()
print(deq)OUTPUT:
deque(['a', 'b', 'c'])
deque(['g', 'a', 'b', 'c', 'z'])
deque(['a', 'b', 'c'])
4. Namedtuple(): The namedtuple function in Python returns a tuple-like object with names for each tuple place. In ordinary tuples, it was used to solve the difficulty of memorizing the index of each field of a tuple object.
Syntax:
class collections.namedtuple()Example:
from collections import namedtuple
Student = namedtuple('Student', 'fname, lname, age')
s1 = Student('Peter', 'James', '13')
print(s1.fname)OUTPUT:
Peter
In above example,an index is not required to print the name of a student rather passing an attribute is sufficient for the required output.
5. ChainMap : ChainMap combines a lot of dictionaries together and returns a list of dictionaries. ChainMaps basically encapsulates a lot of dictionaries into one single unit with no restriction on the number of dictionaries.
Example:
import collectionsdictionary1 = { 'a' : 1, 'b' : 2 }
dictionary2 = { 'c' : 3, 'b' : 4 }
chain_Map = collections.ChainMap(dictionary1, dictionary2)print(chain_Map.maps)OUTPUT:
[{'a': 1, 'b': 2}, {'c': 3, 'b': 4}]
6. OrderedDict(): 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 collectionsd1 = collections.OrderedDict()
d1['A'] = 65
d1['C'] = 67
d1['B'] = 66
d1['D'] = 68
for j,k in d1.items():
print (j,k)OUTPUT:
A 65
C 67
B 66
D 68
In above example, Upon traversing the dictionary, pairs will appear in the order of their insertion.




