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

Paul McGuire ptmcg at austin.rr.com
Fri Feb 22 12:27:56 EST 2008


On Feb 22, 11:20 am, rh0dium <steven.kl... at gmail.com> 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]
    break
else: # only called if we never 'break' out of the for loop
  a.append(element)


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