Last active
August 9, 2020 20:20
-
-
Save raeq/c57a67fbf9ad9561e25e0dbfe1008821 to your computer and use it in GitHub Desktop.
A UserList subclass implementing unique list values.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import UserList | |
class UniquesList(UserList): | |
""" | |
A List Class which works just like a list, except | |
that it only holds unique values - similar to a set. | |
>>> ul = UniquesList("The Jolly Green Giant") | |
>>> print("".join(ul)) | |
The JolyGrniat | |
""" | |
def __init__(self, initlist=None): | |
"""__init__. | |
Args: | |
initlist: | |
""" | |
self.data = [] | |
if initlist: | |
if isinstance(initlist, UniquesList): | |
self.data[:] = initlist.data[:] | |
else: | |
for k in initlist: | |
self.append(k) | |
def append(self, item) -> None: | |
"""Append an item to the end of the list. | |
Args: | |
item: Only unique values are appended, duplicates are omitted | |
Returns: | |
None: | |
""" | |
if not self.data.count(item): | |
super(UniquesList, self).append(item) | |
dl = UniquesList() | |
dl.append("Text Value One") | |
dl.append("Text Value One") | |
dl.append("Text Value One") | |
dl.append("Text Value One") | |
dl.append("Text Value Two") | |
dl.append("Text Value Two") | |
dl.append("Text Value Two") | |
dl.append("Text Value Two") | |
assert len(dl) == 2 | |
dl = UniquesList() | |
dl.append("a" * 1000000000) | |
assert len(dl) == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment