pulling set of unique values from a list

B

Ben Davies

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)[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?
 
S

Stephan Diehl

Ben said:
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:

I'd use a set for that:
from sets import Set
l = [1,1,1,2,2,3,3]
[x for x in Set(l)] [1, 2, 3]

By the way, in a lot of cases where I used lists, I'm now using sets because
they seem more natural in some situations.

Stephan
 
S

Skip Montanaro

Ben> I need to get [1,2,3] from [1,1,1,2,2,3,3] with as little effort
Ben> possible for my CPU (and keyboard).

You didn't say if order was important, but since one solution you posted was
dict-based, I'll assume not. If you're running 2.3 or from CVS, this seems
the most straightforward to me:
[1, 2, 3]

given the new set type. If you are running 2.3 you'll need to import from
the sets module:
>>> from sets import Set as set
>>> list(set([1,1,1,2,2,3,3]))
[1, 2, 3]

Skip
 
E

Erik Max Francis

Ben said:
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?).

No, the dictionary method is more efficient. The list-using algorithm
has O(n^2) behavior, whereas the dictionary-using algorithm is only
O(n).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top