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

Jason tenax.raccoon at gmail.com
Fri Feb 22 12:36:11 EST 2008


On Feb 22, 10: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

How-about using a generator expression and Python's built-in "in"
operator:

>>> def example(myData, newData):
...   if newData[0] not in (x[0]  for x in myData):
...     myData.append( newData )
...
>>> l = []
>>> example( l, ('a', 'apple', 'aviary') )
>>> l
[('a', 'apple', 'aviary')]
>>> example( l, ('s', 'spam', 'silly') )
>>> l
[('a', 'apple', 'aviary'), ('s', 'spam', 'silly')]
>>> example( l, ('s', 'suck-tastic') )
>>> l
[('a', 'apple', 'aviary'), ('s', 'spam', 'silly')]
>>>



More information about the Python-list mailing list