Declaration of an array of unspecified size

Chad Netzer cnetzer at sonic.net
Mon Sep 1 10:10:46 CEST 2003


On Sun, 2003-08-31 at 23:43, Bertel Lund Hansen wrote:
> Ulrich Petri skrev:

> >>     self.mails=len(pop.list()[1])
> >you can skip the "mails" variable. len(mail) will give the same.
> 
> Yes, I saw that in another posting. But I have a habit that I
> aquired working with slow computers: always to substitute
> function-calls with variables (faster). Is that a bad habit?

Yes, because of the word "always".  If you mean that literally, then I
would consider it VERY bad style (sorry; no offense meant).  This habit
can be quite error prone, just because it is possible, even common, for
your length variable to become out of sync with the true list length. 
These kinds of bugs can be very difficult to track down.

It is best to use this habit sparingly, such as when you know your
algorithm won't change the list, and you use the line length several
times in quick succession, or in a small loop.  That kind of thing is
done all the time, on a very limited and local scale, and isn't
necessarily bad.  But don't always do it just for the sake of doing it. 
Only do it where it is a known bottleneck (or you know it will remain
coorect, and it makes the code easier to express)

Python's lists are not 'linked lists', btw, and the length operation is
very fast (O(1)), because the length is always known exactly, and can be
gotten with a fast lookup (ie. it doesn't have to count).  The function
call overhead in python is a bit high, but presumably your program calls
LOTS of functions; a few more len() calls will have virtually no effect,
outside of loops.

Finally, you can google for the term "memoize python" on Google, which
will demonstrate a technique for automatically caching function call
results, which you may find interesting.

-- 
Chad Netzer






More information about the Python-list mailing list