On Mon, 12 Sep 2005 12:52:52 +0200, gabor wrote: > hi, > > there are 2 versions of a simple code. > which is preferred? > > > === > if len(line) >= (n+1): > text = line[n] > else: > text = 'nothing' > === > > > === > try: > text = line[n] > except IndexError: > text = 'nothing' > === > > > which is the one you would use?
Personally, I would use either. You say po-ta-to, I say pot-at-o. try...except... blocks are quick to set up, but slow to catch the exception. If you expect that most of your attempts will succeed, then the try block will usually be faster than testing the length of the list each time. But if you expect that the attempts to write the line will fail more frequently, then testing will be quicker. You will need to do your own testing before hand to find the exact cut-off, and expect that cut-off to vary according to the Python implementation and version. But a rough rule of thumb is, if you expect your code to fail more often than succeed, then test first, otherwise catch an exception. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list