Unique Elements in a List

Edvard Majakari edvard+news at majakari.net
Tue May 10 04:26:16 EDT 2005


"Michael J. Fromberger" <Michael.J.Fromberger at Clothing.Dartmouth.EDU> writes:

> One reasonable solution might be as follows:
>
>   def unique_elts(seq):
>     elts = {}
>     for pos, elt in enumerate(seq):
>       elts.setdefault(elt, []).append(pos)
>
>     return [ (x, p[0]) for (x, p) in elts.iteritems()
>              if len(p) == 1 ]

This is neat. Being lazy (the wrong way) I've never payed much attention why
would I need dict.setdefault() when I have things as dict.get(k, [def]). This
was a nice example of good use for setdefault() because it works like
dict.get() except it also sets the value if it didn't exist.

+1 IOTW (idiom of the week).

-- 
# Edvard Majakari		Software Engineer
# PGP PUBLIC KEY available    	Soli Deo Gloria!

$_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n";



More information about the Python-list mailing list