pulling set of unique values from a list

Ben Davies ben.m.davies at baesystems.com
Wed Jan 14 09:32:34 EST 2004


I need to get [1,2,3] from [1,1,1,2,2,3,3] with as little effort possible
for my CPU (and keyboard).
I'd half expected there to be a list.values method to do this, but there
isn't so I've have had to use a dictionary object:

>>> l=[1,1,1,2,2,2,3,3,3]
>>> dict.fromkeys(l).keys()
[1, 2, 3]

of course another way would be to do it 'by hand' like this:

>>> l=[1,1,1,2,2,2,3,3,3]
>>> values=[]
... for v in l:
...     if not v in values: values.append(v)
>>> values
[1, 2, 3]

personally I prefer the dictionary one-liner, but with the second iterative
way it is probably more obvious what the code is doing (and perhaps more
efficient?).
Is there any better way to do this that I've missed, I was kind of surprised
not to find a values() method on the built-in list type?








More information about the Python-list mailing list