Created
August 13, 2020 10:40
-
-
Save raeq/207c626b77c971ac5e43d53532e7e335 to your computer and use it in GitHub Desktop.
A list of unique elements.
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() | |
for i in range(1000): | |
dl.append("a") | |
assert len(dl) == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment