Inspired by Francesco, answer , instead of creating our own filter() -type function, let us do the built-in work for us:
def unique(a, s=set()): if a not in s: s.add(a) return True return False
Using:
uniq = filter(unique, orig)
This may or may not be faster or slower than the answer, which implements all the work in pure Python. Benchmark and look. Of course, this only works once, but it demonstrates the concept. Of course, the ideal solution is to use a class:
class Unique(set): def __call__(self, a): if a not in self: self.add(a) return True return False
Now we can use it as much as we want:
uniq = filter(Unique(), orig)
Once again, we can (or cannot) throw performance out of the window - the benefits of using the built-in function can be offset by the overhead of the class. I just though it was an interesting idea.
source share