Python collections.UserList



The Python UserList is a container like list present in collections module. This class acts as a wrapper class around the list objects. It is useful when one wants to create a list of their own with some modified functionality or with some new functionality. It can be considered as a way of adding new functionality for the list.

The UserList() takes a list instance as an argument and simulates a list that is kept in a regular list. The list is accessible by the data attribute of the this class.

Syntax

Following is the Syntax of the Python UserList class −

collections.UserList(data)

Parameters

This class accepts list as a parameter.

Return Value

This class returns <class 'collections.UserList'> object.

Example

Following is an basic example of the Python UserList()

# Python program to demonstrate
# userlist
from collections import UserList
List1 = [10, 20, 30, 40]
# Creating a userlist
userlist = UserList(List1)
print(userlist.data)

Following is the output of the above code −

[10, 20, 30, 40]

Inheriting UserList

We can inherit the UserList properties into another class and can modify the functionality and can add new methods into the class.

Example

In the following example we are inheriting the UserList class and disabling the deleting feature −

from collections import UserList
# Creating a List where
# deletion is not allowed
class MyList(UserList):
	
	# Function to stop deletion
	# from List
	def remove(self, s = None):
		raise RuntimeError("Deletion not allowed")
		
	# Function to stop pop from 
	# List
	def pop(self, s = None):
		raise RuntimeError("Deletion not allowed")
	
# Driver's code
list = MyList([11, 21, 31, 41])
print("Original List :",list)
# Inserting to List"
list.append(5)
print("After Insertion :", list)
# Deleting From List
list.remove()

Following is the output of the above code −

Original List : [11, 21, 31, 41]
After Insertion : [11, 21, 31, 41, 5]
Traceback (most recent call last):
  File "/home/cg/root/88942/main.py", line 23, in <module>
    list.remove()
  File "/home/cg/root/88942/main.py", line 9, in remove
    raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
python_modules.htm
Advertisements