Uniquifying a list?

T

Tim Chase

Is there an obvious/pythonic way to remove duplicates from a
list (resulting order doesn't matter, or can be sorted
postfacto)? My first-pass hack was something of the form
>>> myList = [3,1,4,1,5,9,2,6,5,3,5]
>>> uniq = dict([k,None for k in myList).keys()

or alternatively

However, it seems like there's a fair bit of overhead
here...creating a dictionary just to extract its keys, or
creating a set, just to convert it back to a list. It feels
like there's something obvious I'm missing here, but I can't
put my finger on it.

Thanks...

-tkc
 
E

Edward Elliott

You could do
>>> uniq = [x for x in set(myList)]

but that's not really any different than what you already have.

This almost works:
>>> uniq = [x for x in myList if x not in uniq]

except the r-val uniq isn't updated after each iteration.

Personally I think list(set(myList)) is as optimal as you'll get.


Tim said:
Is there an obvious/pythonic way to remove duplicates from a list
(resulting order doesn't matter, or can be sorted postfacto)? My
first-pass hack was something of the form
myList = [3,1,4,1,5,9,2,6,5,3,5]
uniq = dict([k,None for k in myList).keys()

or alternatively

However, it seems like there's a fair bit of overhead here...creating a
dictionary just to extract its keys, or creating a set, just to convert
it back to a list. It feels like there's something obvious I'm missing
here, but I can't put my finger on it.

Thanks...

-tkc
 

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

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,108
Latest member
AlbertEste
Top