473,395 Members | 1,595 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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(files[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 1307
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(files[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(files[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 "brainwashed" 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*******@hotmail.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(cnt, fi)

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
May 25 '06 #6
Nick Craig-Wood wrote:
mik3 <mi*******@hotmail.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(cnt, 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,d2list):
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
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...
11
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...
7
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
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...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...

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.