473,791 Members | 2,827 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using range() in for loops

I'm reading Text Processing in Python right now and I came across a
comment that is helping me to see for loops in a new light. I think
because I'm used to the C-style for loop where you create a counter
within the loop declaration, for loops have always seemed to me to be
about doing something a certain number of times, and not about iterating
over an object.

The reason for this distinction comes from the fact that I read a lot
how using range and for is somewhat discouraged, because it doesn't
really use a for loop for it's true purpose. So my question is, is this
just a Python-oriented opinion about for loops, or is it a general idea?

Also, what if you *do* need to just do something a set number of times.
Is this okay, or does it mean you are approaching the problem
incorrectly? Using for and range together seems to be a common idiom,
yet at the same time discouraged, so I'm wondering what is a good balance.

Thanks.
Apr 5 '06
17 3059
On Tue, 2006-04-04 at 21:54 -0400, John Salerno wrote:
I'm reading Text Processing in Python right now and I came across a
comment that is helping me to see for loops in a new light. I think
because I'm used to the C-style for loop where you create a counter
within the loop declaration, for loops have always seemed to me to be
about doing something a certain number of times, and not about iterating
over an object.
This is a normal reaction. Try to keep in mind that when you use any
"higher level" language your code will closer reflect what you want
rather than how to accomplish what you want. When you are creating a
loop over numbers, is your goal really to count, or to use the integer
that you are counting to do something else, like perhaps dereference
elements of a string.

Also, part of the problem is a preconceived restriction that you hold on
the use of forloops. They arn't just for counting, there are all sorts
of interesting things that can go in there. Remember, a for loop is
basically a while loop with a little bit of syntactic sugar. Look at
this:
for( a, b, c ) {
d;
e;
}

is the same as

a;
while (b)
{
d;
e;
c;
}
C for and while are the same creature. Python's while loop is Python's
version of for/while. If you wanted to mimick C you could write

i = 0
while( i<10 ):
print i
i+=1

but this is clumbsy and slower. for(i=0;i<10;i+ +) is a common enough
programing pattern, you arn't really interested in setting i,
incrementing, doing all of that housekeeping. You really want to repeat
10 times with with i set to 0, 1 ...

for ... xrange does this well and is somewhat the motivation for the
creation of xrange.
The reason for this distinction comes from the fact that I read a lot
how using range and for is somewhat discouraged, because it doesn't
really use a for loop for it's true purpose. So my question is, is this
Nothing in a well defined language has a true purpose. The true purpose
of an int in C isn't to be for loop fodder. One of the hallmarks of a
well designed language is orthogonality; most anything works with
anything else. A feature that has one specific use doesn't provide much
utility to justify the effort used to create it.

just a Python-oriented opinion about for loops, or is it a general idea?
Programming languages borrow from heavily from natural languages; yes,
for is a loaned word from English that exists in C, python ... lots of
languages. But just as when one human language borrows from another,
the resulting semantics are not always the same.

Each as a formal semantic. C and Python are somewhat different, and
yes, you could describe the philosophical difference as a matter of
opinions.

Also, what if you *do* need to just do something a set number of times.
Is this okay, or does it mean you are approaching the problem
incorrectly? Using for and range together seems to be a common idiom,
yet at the same time discouraged, so I'm wondering what is a good balance.


The correct idiom is for( xrange( foo )). This is preferred over range
for efficiency.

Historically there were no iters. If you wanted to do loop you would
say

for x in range( 10 ):
foo
bar

range created a list of 10 items and x marched over them. Creating this
list in advance doesn't need to take any more time; you have to create
the number objects anyway to assign to x at some point, so you might as
well get that done with upfront.

The problem was memory consumption. The memory requirements of the
list put a bound on large your iteration could be.

xrange was created, and soon followed general iters. Now, the range
object generates the numbers on the fly as the loop runs .. the loop
says "hey, whats next" and the next item is returned.

When people say "don't say for x in range" they are really saying "use
xrange instead of range."

Apr 5 '06 #11
AndyL <ask@me> wrote:
Paul Rubin wrote:
Normally you'd use range or xrange. range builds a complete list in
memory so can be expensive if the number is large. xrange just counts
up to that number.

so when range would be used instead of xrange. if xrange is more
efficient, why range was not reimplemented?


If you actually want the list for some reason:

$ python2.4 -mtimeit 'list(xrange(10 0))'
100000 loops, best of 3: 4.54 usec per loop
$ python2.4 -mtimeit 'range(100)'
100000 loops, best of 3: 2.61 usec per loop

--
\S -- si***@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Apr 5 '06 #12
On Wed, 05 Apr 2006 09:16:37 -0400, AndyL wrote:
Paul Rubin wrote:
Normally you'd use range or xrange. range builds a complete list in
memory so can be expensive if the number is large. xrange just counts
up to that number.


so when range would be used instead of xrange. if xrange is more
efficient, why range was not reimplemented?


For historical reasons.

Don't worry, in Python3000, range() will be an iterator, and xrange() will
disappear. Until then, I use range() for small loops (by small I mean
anything up to a few tens of thousands), and xrange() only when I
absolutely have to optimize my code to save a piddling few tens of
kilobytes of memory.
--
Steven.

Apr 5 '06 #13
On Wed, 05 Apr 2006 16:15:12 +0200, Georg Brandl wrote:
su************* *@gmail.com wrote:
hi John,
Python doesn't provide for loop like C / C++ but using Range() or
Xrange() you can achive all the functionalities of the C for loop.


Not quite.


Care to explain what the differences are, or shall we guess?

--
Steven.

Apr 5 '06 #14
On Wed, 05 Apr 2006 16:21:02 +0200, Georg Brandl wrote:
Because of backwards compatibility. range() returns a list, xrange() an
iterator: list(xrange(... )) will give the same results as range(...).


Georg is pretty much correct in his explanation, but just to dot all the
I's and cross all the T's, we should explain that xrange() doesn't return
an iterator, it returns a special xrange object:
x = xrange(1000)
type(x) <type 'xrange'>

xrange existed as a special bit of magic before Python supported
iterators. While xrange objects behave (sort of) like iterators, they
aren't quite the same. For instance, they don't have a next attribute:
x.next Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'xrange' object has no attribute 'next'

whereas iterators do:
i = iter(range(1000 ))
i.next <method-wrapper object at 0xf7054d2c>

Likewise, you can get random access to the items in an xrange object:
x[500] 500

but not in iterators:
i[500]

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsubscriptable object

--
Steven.

Apr 5 '06 #15
Steven D'Aprano wrote:
On Wed, 05 Apr 2006 16:21:02 +0200, Georg Brandl wrote:
Because of backwards compatibility. range() returns a list, xrange() an
iterator: list(xrange(... )) will give the same results as range(...).


Georg is pretty much correct in his explanation, but just to dot all the
I's and cross all the T's, we should explain that xrange() doesn't return
an iterator, it returns a special xrange object:


Ah yes, the old iterator <-> iterable problem ;)

Georg
Apr 5 '06 #16
Steven D'Aprano wrote:
On Wed, 05 Apr 2006 16:15:12 +0200, Georg Brandl wrote:
su************* *@gmail.com wrote:
hi John,
Python doesn't provide for loop like C / C++ but using Range() or
Xrange() you can achive all the functionalities of the C for loop.


Not quite.


Care to explain what the differences are, or shall we guess?


C's for is much more powerful.

for(a; b; c) { d } translates to

a
while b
d
c

which can't be replaced by a simple

for i in range(...)

Georg
Apr 5 '06 #17
Georg Brandl <g.************ *@gmx.net> wrote:
Steven D'Aprano wrote:
On Wed, 05 Apr 2006 16:15:12 +0200, Georg Brandl wrote:
su************* *@gmail.com wrote:
hi John,
Python doesn't provide for loop like C / C++ but using Range() or
Xrange() you can achive all the functionalities of the C for loop.

Not quite.


Care to explain what the differences are, or shall we guess?


C's for is much more powerful.

for(a; b; c) { d } translates to

a
while b
d
c

which can't be replaced by a simple

for i in range(...)


No, but it can be easily replaced by:

# factoring out the loopstructure.. .
def gotcha():
a
while b:
yield c

# ...from the loopbody
for i in gotcha():
d

or several variations thereof. In C++, I almost half-heartedly replace
most of Python's generators' power with C++'s templated iterators, but
when I program in C I find myself really straightjackete d these days in
NOT being able to pull out the "loopstruct ure" as I can in Python (and,
about halfway, in C++).
Alex
Apr 6 '06 #18

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

Similar topics

5
1708
by: Jim Cser | last post by:
Hello- I have a function to generate a multi-dimensional array, which then gets summed over one axis. The problem is that the dimensions are large, and I run out of memory when I create the entire array, so I'm trying to do the sum *within* the function. Example-- variables x,y,z,t; dimensions numX, numY, numZ, numT; functions f1(x,y,z,t), f2(y,z,t); want to calculate f1*f2 and sum over t to get out.
3
1954
by: Carlos Ribeiro | last post by:
As a side track of my latest investigations, I began to rely heavily on generators for some stuff where I would previsouly use a more conventional approach. Whenever I need to process a list, I'm tending towards the use of generators. One good example is if I want to print a report, or to work over a list with complex processing for each item. In both cases, a simple list comprehension can't be used. The conventional approach involves...
11
6603
by: Grasshopper | last post by:
Hi, I am automating Access reports to PDF using PDF Writer 6.0. I've created a DTS package to run the reports and schedule a job to run this DTS package. If I PC Anywhere into the server on where the job is running, the job runs sucessfully, PDF files got generated, everything is good. If I scheduled the job to run at the time that I am not logged into the server, Access is not able to print to the printer. The error is pretty...
29
2880
by: Steve R. Hastings | last post by:
When you compile the expression for i in range(1000): pass does Python make an iterator for range(), and then generate the values on the fly? Or does Python actually allocate the list and then step through it? I was under the impression that recent releases of Python optimize this
45
8579
by: Summercoolness | last post by:
it seems that range() can be really slow: the following program will run, and the last line shows how long it ran for: import time startTime = time.time() a = 1.0
1
2726
by: shilpasharma | last post by:
Hi, Can anybody let me know how I can optimise following Query. Select * from reports where ( exists ( SELECT 1 FROM results_required rr, item_claims_trials ict, results res WHERE ict.t_t_id IN ( 3725 ) and res.rr_rr_id = rr.rr_id AND rr.rt_rt_id = -1 and rr.ict_ict_id = ict.ict_id
2
2214
by: Joe Goldthwaite | last post by:
I've been playing with Python a bit. Doing little performance benchmarks and working with Psyco. It's been fun and I've been learning a lot. For example, in a previous post, I was looking for a way to dynamically add new runtime function to a class. Martin told me to use a class instance variable instead. It turns out that's faster than hard coding a list of functions. Thanks Martin. I read that the range function builds a list and...
50
2540
by: John Salerno | last post by:
I know it's popular and very handy, but I'm curious if there are purists out there who think that using something like: for x in range(10): #do something 10 times is unPythonic. The reason I ask is because the structure of the for loop seems to be for iterating through a sequence. It seems somewhat artificial to use the for loop to do something a certain number of times, like above.
19
6025
by: phill86 | last post by:
Hi I am re-posting this thread because it has become very confusing and I have got some way to solving the problem so it is a slightly different question from the initial thread. here is the original tread http://bytes.com/topic/access/answers/872005-query-date-range Just to clarify what I am trying to achieve....
0
9669
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9515
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10426
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9029
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6776
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5558
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2913
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.