Python Intermediate: How to use the Collections Module in Python part – II

Collection Modules in Python

Python’s collection Module provides various types of containers. A Container is an object that stores different objects and allows you to access and iterate over them. Tuple, List, Dictionary, and other built-in containers are available. This article will go over the various containers provided by the collections module.

Namedtuple in Python

Python includes a container-like dictionaries function called “namedtuple()” in the “collections” module. They, like dictionaries, contain keys that are hashed to a specific value. On the contrary, it supports both key-value and iteration access, which dictionaries do not.

In contrast to regular tuples, which lack names for each position, a named tuple returns a tuple object. Consider a tuple names student, where the first element represents the fname, the second element represents the lname, and the third element represents the DOB. If instead of remembering the index position, you can call the element by using the fname argument, it will be much easier to access the tuples element. The NamedTuple provides this functionality.

Example:

from collections import namedtuple
  
Language = namedtuple('Language',['name','spec','thread'])
S = Language('Python','Backend','Multithreading')
 
print ("The Language name is: ",end ="")
print (S.name)
 
print ("The Language using in: ",end ="")
print (S[1])

Output:

The Language name is: Python
The Language using in: Backend

Deque

Python’s “collections” module is used to implement Deque (Double Ended Queue). Deque is preferred over a list when we need faster append and pop operations from both ends of the container, as deque has an O(1) time complexity for append and pop operations, whereas a list has an O(n) time complexity.

There are two varieties of deque:

  • Input Restricted Deque: Deletion is allowed at both ends but input is restricted at one end.
  • Output Restricted Deque: output is restricted at one end, but insertion is allowed at both ends.

Example:

from collections import deque
  
queue = deque(['Python','Java','Ruby'])
  
print(queue)

Output:

deque(['Python', 'Java', 'Ruby'])

Deque elements can be added from both ends. The right add() function is used to insert elements, and the left appendleft() technique is used to insert elements.

Example:

from collections import deque
  
queue = deque([11,22,33])
  
queue.append(44)
  
print ("Appending 44 at right side: ", end="")
print (queue)
  
queue.appendleft(66)
  
print ("Appending 66 at left side: ", end="")
print (queue)

Output:

Appending 44 at right side: deque([11, 22, 33, 44])
Appending 66 at left side: deque([66, 11, 22, 33, 44])

Elements can be deleted from both ends of the deque. Pop() is used to remove components from the right, and popleft() is used to remove elements from the left.

Example:

from collections import deque
 
queue = deque([66, 11, 22, 33, 44])
 
print("Orginal deque:", queue)
 
queue.pop()
  
print ("Deleting 44 from right side: ", end="")
print (queue)
  
queue.popleft()
 
print ("Deleting 66 from left side: ", end="")
print (queue)

Output:

Orginal deque: deque([66, 11, 22, 33, 44])
Deleting 44 from right side: deque([66, 11, 22, 33])
Deleting 66 from left side: deque([11, 22, 33])

UserDict

Python’s collections module has a dictionary-like container called UserDict. This class serves as a container for dictionary items. This class is handy when one wishes to develop their own dictionary, either with updated or additional capabilities. It can be thought of as a method of adding additional behaviors to the lexicon. This class accepts a dictionary instance as a parameter and simulates the contents of a standard dictionary. This class’s data attribute provides access to the dictionary.

Example:

from collections import UserDict
 
 
queue = {'apple':1,'banana': 2,'cherry': 3}
 
dict_user1 = UserDict(queue)
print(dict_user1.data)
 
dict_user2 = UserDict()
print(dict_user2.data)
 
dict_user1.pop('apple')
print(dict_user1.data)

Output:

{'apple': 1, 'banana': 2, 'cherry': 3}
{}
{'banana': 2, 'cherry': 3}

UserList

The collections module in Python has a List-like container called UserList. This class works as a container for List objects. This class is useful when one wants to design their own list with updated or new functionality. It can be viewed as a method of adding additional behaviors to the list. This class takes a list instance as an argument and simulates a regular list. The data attribute of this class provides access to the list.

Example:

from collections import UserList
 
user_list = [11, 12, 13, 14]
 
userList1 = UserList(user_list)
print("UserList:",userList1.data)
 
 
userList2 = UserList()
print("Empty UserList:",userList2.data)
 
userList2.append(44)
userList2.append(55)
userList2.append(66)
print("After appending:",userList2)
 
 
userList1.remove(11)
print("After removing 11:",userList1)

Output:

UserList: [11, 12, 13, 14]
Empty UserList: []
After appending: [44, 55, 66]
After removing 11: [12, 13, 14]

UserString

Python’s collections module includes a String-like container called UserString. This class serves as a wrapper class for string objects. This class is handy when one wishes to construct their own string with changed or additional capabilities. It can be thought of as a method of adding new behaviors to the string. This class takes any string-convertible parameter and simulates a string whose content is retained in a regular string. This class’s data field provides access to the string.

Example:

from collections import UserString
 
 
nums = 23465237
 
user_string = UserString(nums)
print(user_string.data)
 
 
class Mystring(UserString):
   
   def append(self, s):
       self.data += s
       
   def remove(self, s):
       self.data = self.data.replace(s, "")
   
s1 = Mystring("Python")
print("Original String:", s1.data)
s1.append(" Lover")
print("After Appending:", s1.data)
s1.remove("o")
print("After Removing:", s1.data)

Output:

23465237
Original String: Python
After Appending: Python Lover
After Removing: Pythn Lver
Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.