Nebie: list question, speed

Rick Pasotto rickp at telocity.com
Sat May 5 17:18:08 EDT 2001


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.

Using 'if ergline not in ergfield' instead of 'ergfield.count' should
give closer to the same timings as your try/except.

-- 
"Censorship, like charity, should begin at home, but unlike charity,
it should end there."
		-- Clare Boothe Luce
		   Rick Pasotto email: rickp at telocity.com



More information about the Python-list mailing list