Last active
August 13, 2018 14:51
-
-
Save ehoppmann/29913b5bfce256b31db92f562f35cb6c to your computer and use it in GitHub Desktop.
Returns a list containing only unique elements from original list, with an optional key function
This file contains 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 typing import Iterable, Callable, List | |
def ordered_set(iterable: Iterable, key: Callable=lambda x: x) -> List: | |
""" | |
Returns a new list containing all unique items from the iterable. A custom key function can | |
be specified to customize the uniqueness constraint, for example to return the first unique | |
element from the input list based on the second item in each element, one could pass | |
`lambda x: x[1]`. | |
""" | |
out_list = [] | |
added = set() | |
for val in iterable: | |
if not key(val) in added: | |
out_list.append(val) | |
added.add(key(val)) | |
return out_list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment