COLLECTION IN PYTHON
The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will discuss the different containers provided by the collections module. The collections module is a powerful part of the Python standard library that lets you work with data concisely and efficiently. This tutorial covered three of the classes provided by the collections module including namedtuple , defaultdict , and deque .
The Counter
Counter is a subclass of dictionary object. The Counter() function in collections module takes an iterable or a mapping as the argument and returns a Dictionary. In this dictionary, a key is an element in the iterable or the mapping and value is the number of times that element exists in the iterable or the mapping.
You have to import the Counter class before you can create a counter instance.
from collections import CounterCreate Counter Objects
There are multiple ways to create counter objects. The simplest way is to use Counter() function without any arguments.
cnt = Counter()You can pass an iterable (list) to Counter() function to create a counter object.
list = [1,2,3,4,1,2,6,7,3,8,1]
Counter(list)Finally, the Counter() function can take a dictionary as an argument. In this dictionary, the value of a key should be the 'count' of that key.
Counter({1:3,2:4})You can access any counter item with its key as shown below:
list = [1,2,3,4,1,2,6,7,3,8,1]
cnt = Counter(list)
print(cnt[1])when you print cnt[1], you will get the count of 1.
Output:
3In the above examples, cnt is an object of Counter class which is a subclass of dict. So it has all the methods of dict class.
Apart from that, Counter has three additional functions:
- Elements
- Most_common([n])
- Subtract([interable-or-mapping])
The element() Function
You can get the items of a Counter object with elements() function. It returns a list containing all the elements in the Counter object.
Look at the following example:
cnt = Counter({1:3,2:4})
print(list(cnt.elements()))Output:
[1, 1, 1, 2, 2, 2, 2]Here, we create a Counter object with a dictionary as an argument. In this Counter object, count of 1 is 3 and count of 2 is 4. The elements() function is called using cnt object which returns an iterator which is passed as an argument to the list.
The iterator repeats 3 times over 1 returning three ‘1’s, and repeats four times over 2 returning four ‘2’s to the list. Finally, the list is printed using the print function.
The most_common() Function
Get Harshini M’s stories in your inbox
Join Medium for free to get updates from this writer.
The Counter() function returns a dictionary which is unordered. You can sort it according to the number of counts in each element using most_common() function of the Counter object.
list = [1,2,3,4,1,2,6,7,3,8,1]
cnt = Counter(list)
print(cnt.most_common())Output:
[(1, 3), (2, 2), (3, 2), (4, 1), (6, 1), (7, 1), (8, 1)]You can see that most_common function returns a list, which is sorted based on the count of the elements. 1 has a count of three, therefore it is the first element of the list.
The subtract() Function
The subtract() takes iterable (list) or a mapping (dictionary) as an argument and deducts elements count using that argument.
Namedtuple:
A NamedTuple returns a tuple object with names for each position which the ordinary tuples lack. For example, consider a tuple names student where the first element represents fname, second represents lname and the third element represents the DOB. Suppose for calling fname instead of remembering the index position you can actually call the element by using the fname argument, then it will be really easy for accessing tuples element. This functionality is provided by the NamedTuple.
Syntax:
class collections.namedtuple(typename, field_names)The defaultdict :
The defaultdict works exactly like a python dictionary, except for it does not throw KeyError when you try to access a non-existent key.
Instead, it initializes the key with the element of the data type that you pass as an argument at the creation of defaultdict. The data type is called default_factory.
Import defaultdict:
First, you have to import defaultdict from collections module before using it:
from collections import defaultdictCreate a defaultdict:
You can create a defaultdict with the defaultdict() constructor. You have to specify a data type as an argument. Check the following code:
nums = defaultdict(int)
nums['one'] = 1
nums['two'] = 2
print(nums['three'])Output:
0In this example, int is passed as the default_factory. Notice that you only pass int, not int(). Next, the values are defined for the two keys, namely, 'one' and 'two', but in the next line we try to access a key that has not been defined yet.
In a normal dictionary, this will force a KeyError. But defaultdict initialize the new key with default_factory's default value which is 0 for int. Hence, when the program is executed, and 0 will be printed. This particular feature of initializing non-existent keys can be exploited in various situations.
For example, let’s say you want the count of each name in a list of names given as “Mike, John, Mike, Anna, Mike, John, John, Mike, Mike, Britney, Smith, Anna, Smith”.
from collections import defaultdictcount = defaultdict(int)
names_list = "Mike John Mike Anna Mike John John Mike Mike Britney Smith Anna Smith".split()
for names in names_list:
count[names] +=1
print(count)
Output:
defaultdict(<class 'int'>, {'Mike': 5, 'Britney': 1, 'John': 3, 'Smith': 2, 'Anna': 2})First, we create a defaultdict with int as default_factory. The names_list includes a set of names which repeat several times. The split() function returns a list from the given string. It breaks the string whenever a white-space is encountered and returns words as elements of the list. In the loop, each item in the list is added to the defaultdict named as count and initialized to 0 based on default_factory. If the same element is encountered again, as loop continues, count of that element will be incremented.
Deque:
Deque is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to list with O(n) time complexity.
Syntax:
class collections.deque(list)




