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

Paul McGuire ptmcg at
Fri Feb 22 18:27:56 CET 2008

On Feb 22, 11:20 am, rh0dium <steven.kl... at> wrote:
> 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

for item in a:
  if item[0] == element[0]
else: # only called if we never 'break' out of the for loop

But what about a dict?

adict = dict((elem[0],elem) for elem in a)

if item[0] not in adict:
  adict[item[0]] = item

# need the final list?
a = adict.values()

No list searching, and will scale well if a gets real long.

-- Paul

More information about the Python-list mailing list