Nebie: list question, speed

Werner Hoch werner.ho at gmx.de
Sun May 6 01:20:49 EDT 2001


Rick Pasotto wrote:
> On Sat, 5 May 2001 17:30:59 +0200 in comp.lang.python, Werner Hoch wrote:
> > Hello,
> > 
> > I wrote a little programm parsing two textfiles together.
> > The result is a list without uniq entries:
> > 
> > So i wrote this to check if the entry already exists:
> > --------
> > if ergfield.count(ergline) == 0:
> >       ergfield.append(ergline)
> > ---------
> > execution time is about 45 seconds
> 
> This *always* looks at *every* element in ergfield.
> 
> > an then I tried a second statment which is twice as fast as the first one:
> > ------------
> > try:
> >       ergfield.index(ergline)
> > except:
> >       ergfield.append(ergline)
> > ------------
> > execution time is about 21 seconds
> 
> This stops looking as soon as it finds a match.
> 
> The execution time will vary depending on the order of the input data.
> 
> > I don't like the second solution because it uses the exeption handling like
> > a if statement!
> > Are there better ways to do this?
> 
> Nothing wrong with using try/except.

It looks ugly to me.
> 
> Using 'if ergline not in ergfield' instead of 'ergfield.count' should
> give closer to the same timings as your try/except.
> 
New timings when using this: 22s
try:
      ergfield.index(ergline)
And 29s when using this:
if ergline not in ergfield

I think I will use the second one even if its a little bit slower (because
it looks nicer)

Thanks
werner
-- 
werner.ho at gmx.de
Hi, I´m a .signature antivirus, copy me in 
your ~/.signature file to protect your system



More information about the Python-list mailing list