Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Last active August 29, 2015 13:56
Show Gist options
  • Save carymrobbins/8867308 to your computer and use it in GitHub Desktop.
Save carymrobbins/8867308 to your computer and use it in GitHub Desktop.
Unique iterator for Python.
def identity(x):
return x
class unique(object):
def __init__(self, xs, predicate=identity):
""" :type xs: Iterable """
self._xs = xs
self._predicate = predicate
def __iter__(self):
""" :rtype: Iterable """
p = self._predicate
s = set()
for x in self._xs:
p_x = p(x)
if p_x not in s:
s.add(p_x)
yield x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment