Python UserList
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.
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 UserListdataattribute.
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 listl = ['USD', 'GBP', 'EUR']print(l)# Instantiate a UserList object from the listul = UserList(l)print(ul)# Print out the data type for each instantiated objectprint(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 itemul.append('$')print(ul)# Remove an itemul.remove('$')# Sort the list-like object in ascending orderul.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:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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