insert unique data in a list

Gary Herron gherron at islandtraining.com
Sun Dec 13 13:20:29 EST 2009


mattia wrote:
> Il Sun, 13 Dec 2009 16:37:20 +0000, mattia ha scritto:
>
>   
>> 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)
>>
>> Thanks,
>> Mattia
>>     
>
> Ok, so you all suggest to use a set. Now the second question, more 
> interesting. Why can't I insert a list into a set? I mean, I have a 
> function that returns a list. I call this function several times and 
> maybe the list returned is the same as another one already returned. I 
> usually put all this lists into another list. How can I assure that my 
> list contains only unique lists? Using set does'n work (i.e. the python 
> interpreter tells me: TypeError: unhashable type: 'list')...
>   

Sets can contain *only* hashable objects, but lists are not hashable 
(since they are mutable).

Perhaps, you could convert your list to a tuple first -- tuples *are* 
hashable.

 >>> s = set()
 >>> l = [1,2,3]
 >>> s.add(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
 >>> s.add(tuple(l))
 >>> s
set([(1, 2, 3)])




More information about the Python-list mailing list