In Python 2.2 (don't ask), what's the neatest way to sort a list and remove duplicates?
I can obviously write a function that would sort()
then iterate, but am wondering if there's an idiomatic one-liner.
edit: The list is short, so efficiency is not a concern. Also, the elements are immutable.
For old python versions, and since you're using strings, there's no one-liner I can think of, but a pattern would probably be this, using dictionaries:
def sorted_uniq(your_list):
table = {}
for s in your_list:
table[s] = None
k = table.keys()
k.sort()
return k
Adapted from an ancient ActiveState code snippet thread that Alex Martelli himself wrote several comments on: http://code.activestate.com/recipes/52560/
A shorter way with list comprehensions:
def sort_uniq(alist):
d = {}
mod_list = [d.setdefault(i,i) for i in alist if i not in d]
mod_list.sort()
return mod_list
Aside from Steven's neat (yet slightly unattractive) one liner, I think this heads toward the fewest lines and most idiomatic way of doing it with Python 2.2:
Thanks to Steven Rumbalski in the comments, the 2nd version can be condensed further with python's zip
function:
def sort_uniq(alist):
mod_list = dict(zip(alist,alist)).keys()
mod_list.sort()
return mod_list
If list.sort()
didn't operate by side effect, we'd have a one liner. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With