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.
SyntaxFollowing is the Syntax of the Python UserList class −
collections.UserList(data)Parameters
This class accepts list as a parameter.
Return ValueThis class returns <class 'collections.UserList'> object.
ExampleFollowing 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.
ExampleIn 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4