Skip to content
Related Articles

Related Articles

Collections.UserList in Python
  • Last Updated : 26 Mar, 2020
GeeksforGeeks - Summer Carnival Banner

Python Lists are array-like data structure but unlike it can be homogenous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index.

Note: For more information, refer to Python List


Python supports a List like a container called UserList present in the collections module. This class acts as a wrapper class around the List objects. This class 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 behaviors for the list. This class 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.



Example 1:

# Python program to demonstrate
# userlist
from collections import UserList
L = [1, 2, 3, 4]
# Creating a userlist
userL = UserList(L)
# Creating empty userlist
userL = UserList()


[1, 2, 3, 4]

Example 2:

# Python program to demonstrate
# userlist
from collections import UserList
# Creating a List where
# deletion is not allowed
class MyList(UserList):
    # Function to stop deleltion
    # 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
L = MyList([1, 2, 3, 4])
print("Original List")
# Inserting to List"
print("After Insertion")
# Deliting From List


Original List
After Insertion
[1, 2, 3, 4, 5]
Traceback (most recent call last):
  File "/home/", line 33, in 
  File "/home/", line 15, in remove
    raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :