Python collections.UserList

The class UserList in Python acts as a wrapper around a list-objects. This class is useful when one wants to create a list of their own with some modified functionality. In other words, it can be considered as a way of adding new behaviours to the list. This class takes a list instance as an argument and simulates a list that is kept in a regular list. So, the list is accessible by the data attribute of this class.

Syntax :

The signature for the UserList is as shown below.

collections.UserList([list])

Python UserList Examples:

Example 1: In this example, we will create a UserList using the existing list object. In this case, the list is now available as an attribute.

#Importing UserList 
from collections import UserList 
#Initializing
data = ['Delhi', 'Madhya Pradesh','Maharashtra']
 
ud = UserList(data) 
print(ud.data)

Output

['Delhi', 'Madhya Pradesh','Maharashtra']

Example 2: In this case, we will create a UserList wherein it acts as a wrapper class for a customized list object. Thus, it will let us update attributes to the existing list to the UserList.

#Importing UserList 
from collections import UserList
class info(UserList):
      
    def replace(self, s = None,r=None):
        self.append(r)
        self.remove(s)
      
o = info([100,200,300])
  
print(o)
  
#changing value in list
o.replace(200,"India")
print(o)

Output

[100, 200, 300]
[100, 300, 'India']

Example 3: In this case, we will create a UserList wherein it acts as a wrapper class for a customized list object. Thus, it will let us delete attributes to the existing list to the UserList.

#Importing UserList 
from collections import UserList
#Defining class  
class info(UserList):
      
    def deletevalue(self, s = None):
        self.remove(s)
#Creating object      
o = info([100,200,300])

print(o)
  
#deleting value 
o.deletevalue(200)
print(o)

Output

[100, 200, 300]
[100, 300]

References

Happy Learning 🙂

Leave A Comment