0
0
PythonHow-ToBeginner · 3 min read

How to Use UserList in Python: Simple Guide with Examples

In Python, UserList is a class from the collections module that lets you create your own list-like objects by extending it. You use it by importing UserList and subclassing it to add or change list behavior while keeping list features.
📐

Syntax

The basic syntax to use UserList is to import it from the collections module and create a subclass. You can override methods or add new ones to customize behavior.

  • class MyList(UserList): - defines a new list-like class.
  • def __init__(self, initlist=None): - initializes the list with optional starting items.
  • self.data - the actual list data stored internally.
python
from collections import UserList

class MyList(UserList):
    def __init__(self, initlist=None):
        super().__init__(initlist)

    # You can add or override methods here
💻

Example

This example shows how to create a custom list that only allows adding positive numbers. It uses UserList to keep list features and adds a check in the append method.

python
from collections import UserList

class PositiveList(UserList):
    def append(self, item):
        if item > 0:
            super().append(item)
        else:
            print(f"Cannot add non-positive number: {item}")

# Create an instance
plist = PositiveList([1, 2, 3])
print(plist)  # Shows initial list

plist.append(4)  # Adds 4
plist.append(-1) # Tries to add -1
print(plist)  # Shows updated list
Output
[1, 2, 3] Cannot add non-positive number: -1 [1, 2, 3, 4]
⚠️

Common Pitfalls

Some common mistakes when using UserList include:

  • Not calling super().__init__() in your subclass constructor, which can cause the internal list to not initialize properly.
  • Modifying self.data directly without using list methods, which can break expected behavior.
  • Overriding methods without calling the parent method when needed, losing built-in list functionality.
python
from collections import UserList

# Wrong way: missing super().__init__
class BadList(UserList):
    def __init__(self, initlist=None):
        self.data = initlist or []  # This skips UserList init

bl = BadList([1, 2])
print(bl)  # Might work but can cause issues

# Right way:
class GoodList(UserList):
    def __init__(self, initlist=None):
        super().__init__(initlist)

gl = GoodList([1, 2])
print(gl)
Output
[1, 2] [1, 2]
📊

Quick Reference

FeatureDescription
UserListA wrapper around list to create custom list-like classes
self.dataInternal list storage in UserList subclasses
super().__init__(initlist)Initialize the internal list properly
Override methodsCustomize behavior by overriding list methods like append, insert
Use list methodsCall parent methods with super() to keep list features

Key Takeaways

UserList lets you create custom list-like objects by subclassing it.
Always call super().__init__() to initialize the internal list correctly.
Override methods like append to add custom behavior safely.
Use self.data to access the actual list inside your subclass.
Avoid modifying self.data directly without list methods to prevent bugs.