I have a python list where elements can repeat.
>>> a = [1,2,2,3,3,4,5,6]
I want to get the first n
unique elements from
Assuming the elements are ordered as shown, this is an opportunity to have fun with the groupby
function in itertools:
from itertools import groupby, islice
def first_unique(data, upper):
return islice((key for (key, _) in groupby(data)), 0, upper)
a = [1, 2, 2, 3, 3, 4, 5, 6]
print(list(first_unique(a, 5)))
Updated to use islice
instead of enumerate
per @juanpa.arrivillaga. You don't even need a set
to keep track of duplicates.