insert unique data in a list

Alf P. Steinbach alfps at start.no
Sun Dec 13 18:08:41 CET 2009


* mattia:
> How can I insert non-duplicate data in a list? I mean, is there a 
> particular option in the creation of a list that permit me not to use 
> something like:
> def append_unique(l, val):
>     if val not in l:
>         l.append(val)
> 

How about using a set instead?

   >>> a = {1, 2, 3}
   >>> a
   {1, 2, 3}
   >>> a |= {4}
   >>> a
   {1, 2, 3, 4}
   >>> a |= {4}
   >>> a
   {1, 2, 3, 4}
   >>> _


Cheers,

- Alf



More information about the Python-list mailing list