insert unique data in a list

Chris Rebert clp2 at rebertia.com
Sun Dec 13 20:47:45 EST 2009


On Sun, Dec 13, 2009 at 5:19 PM, knifenomad <knifenomad at gmail.com> wrote:
> On 12월14일, 오전2시57분, mattia <ger... at gmail.com> 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)
>>
>> 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')...
>
> this makes the set type hashable.
>
> class Set(set):
>    __hash__ = lambda self: id(self)

Or you could just use frozenset and get the correct semantics:
http://docs.python.org/library/stdtypes.html#frozenset

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list