Python UserList

Anonymous contributor's avatar
Anonymous contributor
Published Nov 4, 2025
Contribute to Docs

The UserList class from the collections module acts as a wrapper around the built-in list type, to create custom list-like classes with modified behavior or new functionalities. Although directly subclassing Python’s list reduces the need for this class, UserList remains available in the standard library for convenience and backward compatibility.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

collections.UserList([list])

Parameters:

  • list: A regular list object used to store the contents of the UserList class. The list is empty by default and can be accessed via the UserList data attribute.

Return value:

Returns a collections.UserList instance that behaves like a standard Python list.

Example: Basic Usage of collections.UserList

This example showcases a basic use of UserList as a wrapper around a list:

from collections import UserList
# Create a regular list
l = ['USD', 'GBP', 'EUR']
print(l)
# Instantiate a UserList object from the list
ul = UserList(l)
print(ul)
# Print out the data type for each instantiated object
print(type(l))
print(type(ul))

The code returns the following output:

['USD', 'GBP', 'EUR']
['USD', 'GBP', 'EUR']
<class 'list'>
<class 'collections.UserList'>

The UserList behaves like a standard list, but its contents are stored in the data attribute:

print(ul.data) # Access the underlying list
# Append a new item
ul.append('$')
print(ul)
# Remove an item
ul.remove('$')
# Sort the list-like object in ascending order
ul.sort()
print(ul)

The above code will return the following output:

['USD', 'GBP', 'EUR']
['USD', 'GBP', 'EUR', '$']
['EUR', 'GBP', 'USD']

Codebyte Example: Creating a Custom List Using UserList

The following example demonstrates how UserList can be subclassed to restrict unwanted behavior, here, preventing negative numbers from being added:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours