From: ivanlan at callware.com (Ivan Van Laningham)
Date: Fri, 23 Apr 1999 19:03:15 GMT
Subject: Style/efficiency question using 'in'
References: <3720B3B9.98BED320@earth.ox.ac.uk>
Message-ID: <3720C3F3.CFF6D739@callware.com>
Content-Length: 1546
X-UID: 1329                                                  

Pythonistas--

Nick Belshaw wrote:
> 
> If someone could spare a mo to clarify -
> 
> If I do something like :-
> 
> ------------------
> def  func1():
>     return 1,2,3,4,5,6,7,8
> 
> for x in func1():
>     print x
> ------------------
> 
> it works as expected but is the use of a function in a loop undesirable?
> Is the function called once to build the loop or is it called each loop
> increment and therefore undesirable if there is much overhead?
> 

l = (1,2,3,4,5,6,7,8)
for x in l:
	print x

or

for x in 1,2,3,4,5,6,7,8:
	print x

And your version, are all the same.  In each case, a tuple is created;
in the middle case, the tuple is named.  There is no ``loop
increment''--for just steps through the items in the sequence that it
sees in the order that it sees them.  That's why handing for a reversed
list doesn't produce unexpected behaviour.

The only undesirable effects of these three methods are that in (1), you
have created a named function that may only be used once; in (2), I
created a named variable which may only be used once;  and in (3), the
tuple has no name and ceases to exist at the end of the for loop.  Of
course, that means you can't use the tuple again, either;-)

<python-aint-C-C?>-ly y'rs,
Ivan
----------------------------------------------
Ivan Van Laningham
Callware Technologies, Inc.
ivanlan at callware.com
http://www.pauahtun.org
See also: 
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
----------------------------------------------




