check if the values are prensent in a list of values

George Sakkis george.sakkis at gmail.com
Tue Sep 9 14:58:48 EDT 2008


On Sep 9, 2:04 pm, flit <superf... at gmail.com> wrote:

> Hello All,
>
> I will appreciate the help from the more skillfull pythonistas..
>
> I have a small app that generates a sequence like
>
> 00341
> 01741
> 03254
>
> This values I am putting in a list.
>
> So I have a list = [00341,01741,03254]
>
> after the programs find the sequence 03401 this sequence is "new" so
> it appends on the list. But I want to avoid that as the   values are
> already on the first sequence of the list (00341).
> If I try to  use a "in" statement it will give false. as 00341 is
> different from 00341 (but for my goal not..)
>
> How can I check against this list and avoid to put "different"
> sequences but same values?
>
> as 34100 --> dont append on the list
> 14300 ---> dont append on the list
> 05321 --> append to the list.
>
> Am I doing some conceptual error using lists?
> There is a better approach?

Whenever you want to keep track of unique values, think of using a set
or dict, not list. Since you don't care about the character order
within each string, sort the characters so that two strings are
equivalent if and only if their sorted character lists are equal.

One more thing to bear in mind is that the elements of a set (or the
keys of a dict) have to be hashable. Lists are not hashable so there
needs to be an extra step to convert the sorted list into an
"equivalent" hashable object. A common choice that works for any list
[*] is to convert it to a tuple. An alternative that works for strings
only is to join() them into a single string:

>>> values = '00341 01741 03254 34100 14300 05321'.split()
>>> set(''.join(sorted(v)) for v in values)
set(['01235', '00134', '01147', '02345'])

HTH,
George

[*] Assuming that every element of the list is hashable.



More information about the Python-list mailing list