Skip to content

Instantly share code, notes, and snippets.

@ehoppmann
Last active August 13, 2018 14:51
Show Gist options
  • Save ehoppmann/29913b5bfce256b31db92f562f35cb6c to your computer and use it in GitHub Desktop.
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
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