beginner, idiomatic python

Paul McGuire ptmcg at austin.rr.com
Sat Aug 25 21:05:22 EDT 2007


On Aug 23, 11:50 pm, "bambam" <da... at asdf.asdf> wrote:
> Thank you, so generallizing:
>
> (1) Python re-evaluates the loop range on every loop, and
> (2) Python does short-circuit evaluation of conditions, in predictable
> order.
>
> Sorry about the bad question.
>

A beginner would do well to work through the Python Tutorial (http://
docs.python.org/tut/tut.html).  I think your first "insight" is
actually incorrect, if I understand your wording.  If I wrote:

for i in range(1000000000):
    # do something with i

I'm quite certain that range(1000000000) is not evaluated on every
loop iteration.  In fact, the range call generates a list containing
the values [0, 1, 2, ..., 999999999], and then for iterates over this
list.  You can read this at http://docs.python.org/tut/node6.html#SECTION006300000000000000000.

On the other hand, if you are talking about a while loop, of course
the condition is evaluated on every loop - otherwise such a loop, once
entered, would never exit.

Your second generalization is stated pretty plainly in
http://docs.python.org/tut/node7.html#SECTION007700000000000000000.
In fact, conditional short-circuiting is a consistent theme in most
Python functions and structures.  The new any() and all() built-ins in
Python 2.5 for example, evaluate a list of values for their boolean
True/False-ness, any() returning True if any list entry is True,
otherwise False; and all() returning True if all entries are True,
otherwise False.  Both short-circuit their evaluation, so that if the
first element of a billion element list gives a True value for any()
(or a False value for all()), then the evaluation of the remaining
billion-1 items is skipped.

Best of luck in your new Python learning process,
-- Paul




More information about the Python-list mailing list