Simple - looking for a way to do an element exists check..

Paul McGuire ptmcg at austin.rr.com
Fri Feb 22 12:31:53 EST 2008


On Feb 22, 11:20 am, rh0dium <steven.kl... at gmail.com> wrote:
> Hi all,
>
> I have a simple list to which I want to append another tuple if
> element 0 is not found anywhere in the list.
>
> element =  ('/smsc/chp/aztec/padlib/5VT.Cat',
>   '/smsc/chp/aztec/padlib',
>   '5VT.Cat', (33060))
>
> element1 =  ('/smsc/chp/aztec/padlib/5VT.Cat2',
>   '/smsc/chp/aztec/padlib',
>   '5VT.Cat2', (33060))
>
> a =  [ ('/smsc/chp/aztec/padlib/5VT.Cat',
>   '/smsc/chp/aztec/padlib',
>   '5VT.Cat', (33060)),
>  ('/smsc/chp/aztec/padlib/padlib.TopCat%',
>   '/smsc/chp/aztec/padlib',
>   'padlib.TopCat%', (33204)),
>  ('/smsc/chp/aztec/padlib/Regulators.Cat%',
>   '/smsc/chp/aztec/padlib',
>   'Regulators.Cat%', (33204))]
>
> So my code would look something like this.
>
> found = False
> for item in a:
>   if item[0] == element[0]
>     found = True
>     break
> if not found:
>   a.append(element)
>
> But this is just ugly - Is there a simpler way to interate over all
> items in a without using a found flag?
>
> Thanks

Well, that's what I get for typing before thinking...

If the remaining items in each element tuple are the same for any
given element[0], then just use a set.

aset = set(a)
for element in list_of_new_element_tuples:
  aset.add(element)

-- Paul



More information about the Python-list mailing list