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
n
Given
import itertools as it a = [1, 2, 2, 3, 3, 4, 5, 6]
Code
A simple list comprehension (similar to @cdlane's answer).
[k for k, _ in it.groupby(a)][:5] # [1, 2, 3, 4, 5]
Alternatively, in Python 3.6+:
list(dict.fromkeys(a))[:5] # [1, 2, 3, 4, 5]