473,545 Members | 1,890 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

a good explanation

hi
my friend has written a loop like this
cnt = 0
files = [a,b,c,d]
while cnt < len(files) :
do_something(fi les[cnt])

i told him using
for fi in files:
do_something(fi )

is better, because the while loop method makes another call to
len..which is slower..
am i partly right? or is there a better explanation for using the for
method.?
thanks

May 25 '06 #1
7 1311
Bas
I guess that your version is faster, although the difference would be
negligible in this small example. The for loop is probably optimized
for speed under the hood (it is written in C), while the 'while' loop
is performed in python, which is much slower.

Much more important than the speed difference is the clarity: your
version is the accepted practice in the python world, so people will
understand it immediately. It also saves two lines of code. And most of
all, it prevents you from making mistakes: your friend, for example,
has forgotten to increase cnt, so he created an infinite loop!

Bas

May 25 '06 #2
s9************@ yahoo.com schrieb:
hi
my friend has written a loop like this
cnt = 0
files = [a,b,c,d]
while cnt < len(files) :
do_something(fi les[cnt])

i told him using
for fi in files:
do_something(fi )

is better, because the while loop method makes another call to
len..which is slower..
am i partly right? or is there a better explanation for using the for
method.?


Several good reasons:

- his loop won't terminate, as he (or you trying to copy his efforts)
forgot to increment cnt

- he needs additional statements & state. The more you have of this,
the likelier you make errors. he could for example write <= len(files)

- the whole loop is noisier to the eye, makes it harder to grasp what
it's all about

It seems that your friend comes from a language like C or JAVA (pre 1.5)
where the for loop was basically what his while loop above is: one
initializer, one condition test, one last statement, mostly incrementing
the counter.

Python's for is build around the concept of an iterable. Which lists,
tuples, strings and many other things are - and thus the last, and
possibly strongest reason is: its not idiomatic Python, he tries top
shoehorn python into some schemes he's used from other languages. Don't
do that, accept Python & it's ways for a better life :)
Diez

May 25 '06 #3
On 25/05/2006 9:27 PM, s9************@ yahoo.com wrote:
hi
my friend has written a loop like this
cnt = 0
files = [a,b,c,d]
while cnt < len(files) :
do_something(fi les[cnt])

i told him using
for fi in files:
do_something(fi )

is better, because the while loop method makes another call to
len..which is slower..
am i partly right? or is there a better explanation for using the for
method.?

You are partially right.
More reasons:
(1) It's more elegant; you don't have the "cnt" if you don't need it,
there's no extraneous evaluation of len(files).
(2) You don't get the chance to omit cnt += 1, like your friend did
(ROTFLMAO).
Cheers,
John
May 25 '06 #4
wow!...thanks for both replies..and yes you are right, he comes from a
world of C and java...i have successfully "brainwashe d" him to try out
coding in python...haha.
So he has written his first program in python and i have roughly toook
a glance at it and saw what he did.. i pointed out his "mistakes" but
couldn't convince him otherwise. Anyway , i am going to show him your
replies..
thanks again.

May 25 '06 #5
mik3 <mi*******@hotm ail.com> wrote:
So he has written his first program in python and i have roughly toook
a glance at it and saw what he did.. i pointed out his "mistakes" but
couldn't convince him otherwise. Anyway , i am going to show him your
replies..


You might want to show him this too...if you happen to need cnt in the
loop, this is what you write

files = [a,b,c,d]
for cnt, fi in enumerate(files ):
do_something(cn t, fi)

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
May 25 '06 #6
Nick Craig-Wood wrote:
mik3 <mi*******@hotm ail.com> wrote:
So he has written his first program in python and i have roughly toook
a glance at it and saw what he did.. i pointed out his "mistakes" but
couldn't convince him otherwise. Anyway , i am going to show him your
replies..


You might want to show him this too...if you happen to need cnt in the
loop, this is what you write

files = [a,b,c,d]
for cnt, fi in enumerate(files ):
do_something(cn t, fi)

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick


Like many things in Python, measurement is the key, Being an old C
coder. I quite often write:

i=0
while i<end_condition :
something=stuff[i]
i++

and try to be a good pythonesita translate it to:
for something in stuff:
#stuff code

A few weeks ago I found myself manipulating a list of lists that I
wanted to use as columns and discovered that in:

def resort(list,d2l ist):
newlist=[]
"""
while (i < d2len):
newlist.append( list[d2list[i][1]])
i+=1
"""
for row in d2list:
newlist.append( list[row[1]])
return newlist
ran as fast with the while as the for. However, for 'elegance', and to
stick to python style, I kept the for.

Something that is being missed is the idea of changing conditions. A
for loop assumes known boundaries.

def condition_test( ):
# check socket status
# return true if socket good, false otherwise

while condition_test( ):
# do stuff

allows the loopiing code to react to changing conditions. Which of
couse is why we like to keep while loops around ;-0

Curtis

May 26 '06 #7
> Something that is being missed is the idea of changing conditions. A
for loop assumes known boundaries.

def condition_test( ):
# check socket status
# return true if socket good, false otherwise

while condition_test( ):
# do stuff

allows the loopiing code to react to changing conditions. Which of
couse is why we like to keep while loops around ;-0


You can always use break to, well, break out of the loop - and as for is
working over iterables which might very well be generators that deliver
an infinite amount of data, the break-condition can (and often will,
even if one used while) work on the current object instead of some
otherwise unsused index.

So above becomes:
for item in items:
if condition(item) :
break
...

where the while would be still pretty ugly IMHO :)
Diez
May 26 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
3246
by: David MacQuigg | last post by:
I'm concerned that with all the focus on obj$func binding, &closures, and other not-so-pretty details of Prothon, that we are missing what is really good - the simplification of classes. There are a number of aspects to this simplification, but for me the unification of methods and functions is the biggest benefit. All methods look like...
11
2243
by: Alan Silver | last post by:
Hello, I am a seasoned Classic ASP programmer who is interested in learning ASP.NET. I bought a book (Que's Special Edition Using ASP.NET) which is complete rubbish, and would like a recommendation of something better. I have a very basic idea of how ASP.NET works having spent a couple of days playing with it, but it's still a large...
7
1299
by: lasaihome | last post by:
my teacher gave us a homework that to ask a problem on Google. my question is ''how to fabricate a good computer?''
22
3389
by: Jon Skeet [C# MVP] | last post by:
I'm looking to write a C# book fairly soon, and the publisher I've approached wants me to do a bit of market research to find out what people like and don't like in this kind of book. I've read loads of reviews of best-selling books on Amazon, so I've got some ideas from there, but I'd be very interested in hearing what you all think makes...
0
7668
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7923
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7773
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5343
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4960
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3466
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1025
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
722
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.