473,780 Members | 2,137 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 #1
17 3057
John Salerno <jo******@NOSPA Mgmail.com> writes:
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?


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.
Apr 5 '06 #2
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.If
you wants distributed for loop You can use Xrange.
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.

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 #3
John Salerno wrote:
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?
The use of range in for loops is not discouraged, just the unnecessary
use of it. In many languages, you were forced to use range - or size,
or length, or count, etc - because the only practical method of
iteration was to use successive indices into the array or other
collection, stopping when the indexes run out. Most loops operate on
some sort of structure in this way.

In Python, you can iterate directly over the structure instead, so you
no longer have to worry about keeping track of the current index,
comparing it to the maximum index, or collecting the right object from
the structure according to its index. Python just gives you the next
object until there are none left. As a result, for most looping tasks,
you have no need to use range or an equivalent.
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?


Do you really need to do something "a number of times"? If so, range
(or xrange) is perfect for the job. More often though, you need to do
something "once for every <whatever>", so put your 'whatevers' in a
list and iterate over that.

--
Ben Sizer

Apr 5 '06 #4
Ant
It's not just a Python thing, Java for example generally uses the
idiom:

for (Iterator it = list.iterator() ; it.hasNext(); ) {
Object next = it.next();
//Do stuff to next
}

Horrible compared to the python idiom of course (though the latest
version supports for (x : list){})

Ruby has something similar in:

list.each do |item|
print item
end

Again, not as nice as the python idiom IMHO (Though there may be better
ways - I don't know Ruby very well).

So really, all modern programming languages seem to prefer the
loop-over-iterator idiom in preference to looping over a numerical
range.

Apr 5 '06 #5
John Salerno schreef:
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.


I felt more or less the same when I first learned Python; I was also
used to C-style loops, coming from a C/C++ background. In the end
though, it turned out to be a non-issue for me.

In many cases loops really are for iterating over sequences; more so
than I realized when using for loops in C or C++. In these cases,
Python's for statement works better than C-style loops. And if you
really need to do something a certain number of times, there's still
range() or xrange() to do it.

It's quite simple, I think:
- You have a sequence or iterator to loop over? Use for x in sequence.
- You want something done a set number of times? Use for i in range().
- You want to loop over a sequence and also need the index? Use for i, x
in enumerate(seque nce).

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Apr 5 '06 #6
Roel Schroeven wrote:
In many cases loops really are for iterating over sequences; more so
than I realized when using for loops in C or C++. In these cases,
Python's for statement works better than C-style loops. And if you
really need to do something a certain number of times, there's still
range() or xrange() to do it.


Yeah, I'm starting to see the distinction now. I think one thing that
confused me was that C# had two separate loops for these
functionalities , the for loop and the foreach loop (which is equivalent
to Python's for). But even when just doing something a number of times
(C#'s for, Python's for), it looks much cleaner in Python because you
don't have the long, messy three-part for statement.
Apr 5 '06 #7
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?

Apr 5 '06 #8
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.

Georg
Apr 5 '06 #9
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?


Because of backwards compatibility. range() returns a list, xrange() an
iterator: list(xrange(... )) will give the same results as range(...).

In for loops, using xrange instead of range makes no difference since the
loop only iterates over the range. But it's a problem when someone just
does

l = range(100)

and assumes that he's got a list, probably doing

l.remove(5)

and so on.

In Python 3000, plans are that range() will be the same as xrange() is now,
and anyone needing a list can call list(range(...) ).

Georg
Apr 5 '06 #10

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
1953
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
6600
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
8576
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
2725
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
6023
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
10306
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
10139
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...
1
10075
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9931
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7485
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
5373
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2869
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.