473,669 Members | 2,514 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why I don't like range/xrange

Hello!

Many times I was suggested to use xrange and range instead of the
while constructs, and indeed, they are quite more elegant - but, after
calculating the overhead (and losen flexibility) when working with
range/xrange, and while loops, you get to the conclusion that it isn't
really worth using range/xrange loops.

I'd like to show some examples and I'll be glad if someone can suggest
some other fixes than while a loop :-)

a) range overfllow :
for i in range(0, 1 << len(S)) :
......
OverflowError: range() result has too many items

ok, so we fix this one with xrange !

b) xrange long int overflow :

for i in xrange(0, 1 << len(S)) :
.........
OverflowError: long int too large to convert to int

Next thing I miss is the flexibility as in C for loops :

for (i = 0; some_function() /* or other condition */ ; i++)

or,

for (i = 0 ; i < 10 ; i++)
i = 10;
I don't think range/xrange sucks, but I really think there should be
some other constructs to improve the looping flexibility. Other thing
may be, that I just miss an equally elegant alternative that's why I'd
like to hear some suggestions on how to fix the above issues.. (btw,
I've already browsed the archives related to my issue,but i don't see
any good solution)

Thanks

Jernej.

Feb 16 '07 #1
17 2704
On 16 Feb 2007 07:30:15 -0800, stdazi <st****@gmail.c omwrote:
Hello!

Many times I was suggested to use xrange and range instead of the
while constructs, and indeed, they are quite more elegant - but, after
calculating the overhead (and losen flexibility) when working with
range/xrange, and while loops, you get to the conclusion that it isn't
really worth using range/xrange loops.

I'd like to show some examples and I'll be glad if someone can suggest
some other fixes than while a loop :-)

a) range overfllow :
for i in range(0, 1 << len(S)) :
.....
OverflowError: range() result has too many items

ok, so we fix this one with xrange !

b) xrange long int overflow :

for i in xrange(0, 1 << len(S)) :
........
OverflowError: long int too large to convert to int
xrange should be able to handle this. It's probably worth a bug report.
Next thing I miss is the flexibility as in C for loops :

for (i = 0; some_function() /* or other condition */ ; i++)
You'd use a regular for or a while loop here, without the loop index.
or,

for (i = 0 ; i < 10 ; i++)
i = 10;
This doesn't do anything as written. For all reasonable uses of it,
you can do it the same way in Python. Writing C code in Python is a
waste of time and an exercise in frustration.
>
I don't think range/xrange sucks, but I really think there should be
some other constructs to improve the looping flexibility. Other thing
may be, that I just miss an equally elegant alternative that's why I'd
like to hear some suggestions on how to fix the above issues.. (btw,
I've already browsed the archives related to my issue,but i don't see
any good solution)
Enumeration over range() and xrange() is rare in Python. loops like:

data = [...]
for ii in xrange(len(data )):
datum = data[ii]

are a wart. Enumerate over whatever you're going to work with.

In some cases, you want the index and the item. Use enumerate for that:

for index, datum in enumerate(data) :
....
Feb 16 '07 #2
On Feb 16, 9:30 am, "stdazi" <std...@gmail.c omwrote:
Hello!

Many times I was suggested to use xrange and range instead of the
while constructs, and indeed, they are quite more elegant - but, after
calculating the overhead (and losen flexibility) when working with
range/xrange, and while loops, you get to the conclusion that it isn't
really worth using range/xrange loops.

I'd like to show some examples and I'll be glad if someone can suggest
some other fixes than while a loop :-)

a) range overfllow :

for i in range(0, 1 << len(S)) :
.....
OverflowError: range() result has too many items

ok, so we fix this one with xrange !

b) xrange long int overflow :

for i in xrange(0, 1 << len(S)) :
........
OverflowError: long int too large to convert to int

Next thing I miss is the flexibility as in C for loops :

for (i = 0; some_function() /* or other condition */ ; i++)

or,

for (i = 0 ; i < 10 ; i++)
i = 10;

I don't think range/xrange sucks, but I really think there should be
some other constructs to improve the looping flexibility. Other thing
may be, that I just miss an equally elegant alternative that's why I'd
like to hear some suggestions on how to fix the above issues.. (btw,
I've already browsed the archives related to my issue,but i don't see
any good solution)

Thanks

Jernej.
Very little of my own code uses range or xrange, most of my for loops
iterate over a sequence or generator, as in "for item in blahList: do
something with item". I think range/xrange are common beginner's
constructs, since they reflect a more C-like looping method ("for i in
range(len(blahL ist)): do something with blahList[i]").

I really would *not* encourage use of range/xrange, but feel that
iteration over sequences and generators is the more elegant/Pythonic
way to go - who is suggesting you use range/xrange?

For that matter, just what is it you plan to do 2**len(S) times? If S
is of any significant length, the sun may be a lump of coal before you
are finished, regardless of what loop mechanism you use (although it
would make sense to avoid range's implementation of creating a list of
2**len(S) items - fortunately the implementation already resolves this
problem by raising a "that's too many items" exception, and thankfully
so).

Maybe instead of working around range/xrange, you should think whether
a 2**len(S) approach to your problem is feasible in the first place.

-- Paul

Feb 16 '07 #3
stdazi wrote:
Hello!

Many times I was suggested to use xrange and range instead of the
while constructs, and indeed, they are quite more elegant - but, after
calculating the overhead (and losen flexibility) when working with
range/xrange, and while loops, you get to the conclusion that it isn't
really worth using range/xrange loops.

I'd like to show some examples and I'll be glad if someone can suggest
some other fixes than while a loop :-)

a) range overfllow :
for i in range(0, 1 << len(S)) :
.....
OverflowError: range() result has too many items

ok, so we fix this one with xrange !

b) xrange long int overflow :

for i in xrange(0, 1 << len(S)) :
........
OverflowError: long int too large to convert to int

Next thing I miss is the flexibility as in C for loops :

for (i = 0; some_function() /* or other condition */ ; i++)

or,

for (i = 0 ; i < 10 ; i++)
i = 10;
I don't think range/xrange sucks, but I really think there should be
some other constructs to improve the looping flexibility. Other thing
may be, that I just miss an equally elegant alternative that's why I'd
like to hear some suggestions on how to fix the above issues.. (btw,
I've already browsed the archives related to my issue,but i don't see
any good solution)

Thanks

Jernej.
Your example of for i in xrange(0, 1<<len(s)): must have resulted in
a number greater than 1 billion. Are you really doing this much or
are you just pointing out an edge case here?

You can always use while loop:

i=0
while i < (1<<len(s)):
i+=1
or

i=1
while 1:
if i == 10: break
i+=1

Personally I use a lot of for loops in my code where I iterate
over lists or with a generator as my target that returns instances
of my data until exhausted and find the code easy to read:

for line in myfile:
# do something with the line

No need to even "think" about numbers here unless I want to keep
track of the line numbers in which case I would do:

for linenumber, line in enumerate(myfil e):
# do something with each linenumber, line

I find that I use i, j, k pointers less and less as I write more code in
Python. I guess it is just what you get accustomed to using.

-Larry

Feb 16 '07 #4
On Fri, 16 Feb 2007 07:30:15 -0800, stdazi wrote:
Hello!

Many times I was suggested to use xrange and range instead of the
while constructs, and indeed, they are quite more elegant - but, after
calculating the overhead (and losen flexibility) when working with
range/xrange, and while loops, you get to the conclusion that it isn't
really worth using range/xrange loops.
I prefer to _measure_ the overhead instead of guessing.

import timeit
whileloop = """i = 0
while i < N:
i += 1
pass
"""
forloop = """for i in xrange(N):
pass
"""

Now let's see how fast the loops are.
>>timeit.Timer( whileloop, "N = 10000").repeat( 3, 1000)
[3.5716907978057 861, 3.5263650417327 881, 3.5975079536437 988]
>>timeit.Timer( forloop, "N = 10000").repeat( 3, 1000)
[1.3608510494232 178, 1.3419611454010 01, 1.3180010318756 104]

Looks to me that a for loop using xrange is more than twice as fast as a
while loop. The advantage is about the same for small N:
>>timeit.Timer( whileloop, "N = 100").repeat(3 , 1000)
[0.0522642135620 11719, 0.0493741035461 42578, 0.0419459342956 54297]
>>timeit.Timer( forloop, "N = 100").repeat(3 , 1000)
[0.0122590065002 44141, 0.0135121345520 01953, 0.0151968002319 33594]
What makes you think that a while loop has less overhead?
I'd like to show some examples and I'll be glad if someone can suggest
some other fixes than while a loop :-)

a) range overfllow :
for i in range(0, 1 << len(S)) :
.....
OverflowError: range() result has too many items

ok, so we fix this one with xrange !

By the way, you don't need to write range(0, N). You can just write
range(N).

Yes, you're correct, range(some_enor mous_number) will fail if
some_enormous_n umber is too big.
b) xrange long int overflow :

for i in xrange(0, 1 << len(S)) :
........
OverflowError: long int too large to convert to int

Are you really doing something at least 2147483647 times? I'm guessing
that you would be better off rethinking your algorithm.
Next thing I miss is the flexibility as in C for loops :

for (i = 0; some_function() /* or other condition */ ; i++)
This would be written in Python as:

i = 0
while some_function() :
i += 1

A more flexible way would be to re-write some_function() as an iterator,
then use it directly:

for item in some_function() :
# do something with item
or,

for (i = 0 ; i < 10 ; i++)
i = 10;

This would be written in Python as:

for i in xrange(10):
i = 10
I don't think range/xrange sucks, but I really think there should be
some other constructs to improve the looping flexibility.
Every loop can be turned into a while loop. If you have while, you don't
_need_ anything else.

But for elegance and ease of use, a small number of looping constructs is
good. Python has:

while condition:
block
else:
# runs if while exits *without* hitting break statement
block
for item in any_sequence:
block
else:
# runs if for exits *without* hitting break statement
block
Nice, clean syntax.

any_sequence isn't limited to mere arithmetic sequences -- it can be any
sequence of any objects. But if you need a C-style for loop, using
integers, range/xrange([start, ] stop [, step]) is provided.
--
Steven.

Feb 16 '07 #5
On Feb 16, 4:30 pm, "stdazi" <std...@gmail.c omwrote:
for (i = 0; some_function() /* or other condition */ ; i++)
C's "for(pre,cond,p ost) code" is nothing more, then shorthand form of
"pre; while(cond) {code; post;}"
Which translated to Python would be:

pre
while cond:
code
post

Feb 16 '07 #6
In <pa************ *************** *@REMOVE.THIS.c ybersource.com. au>, Steven
D'Aprano wrote:
>for (i = 0 ; i < 10 ; i++)
i = 10;


This would be written in Python as:

for i in xrange(10):
i = 10
Nope, in Python it's:

for i in xrange(10):
break

I think his example should demonstrate that assigning to the loop variable
has no effect on the "loop test". Which IMHO is a good thing.

Ciao,
Marc 'BlackJack' Rintsch
Feb 16 '07 #7
stdazi wrote:
Many times I was suggested to use xrange and range instead of the
while constructs, and indeed, they are quite more elegant - but,
after calculating the overhead (and losen flexibility) when
working with range/xrange, and while loops, you get to the
conclusion that it isn't really worth using range/xrange loops.
How did you calculate that?
b) xrange long int overflow :

for i in xrange(0, 1 << len(S)) :
........
OverflowError: long int too large to convert to int
Why do you bit shift a len result here? Just to get a huge number?
Try the same with C. You'd get an integer overflow in the first
place.

But this long int =int issue should not exist in a future python
version any more, IIRC int and long int is scheduled to be merged
somehow. (Or isn't it?)

Regards,
Björn

--
BOFH excuse #203:

Write-only-memory subsystem too slow for this machine. Contact your
local dealer.

Feb 16 '07 #8
But this long int =int issue should not exist in a future python
version any more, IIRC int and long int is scheduled to be merged
somehow. (Or isn't it?)
It is done.
http://mail.python.org/pipermail/pyt...ry/000251.html
--
EduardoOPadoan (eopadoan->altavix::com )
Bookmarks: http://del.icio.us/edcrypt
Feb 16 '07 #9
On 2007-02-16, Bart Ogryczak <B.********@gma il.comwrote:
On Feb 16, 4:30 pm, "stdazi" <std...@gmail.c omwrote:
>for (i = 0; some_function() /* or other condition */ ; i++)

C's "for(pre,cond,p ost) code" is nothing more, then shorthand form of
"pre; while(cond) {code; post;}"
Which translated to Python would be:

pre
while cond:
code
post
No, when you consider the continue statement, which which Python
also supports.

for (pre; cond; post) {
continue;
}

That's not an infinite loop in C, but the Python while-loop
version would be.

--
Neil Cerutti
Feb 16 '07 #10

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

Similar topics

2
24456
by: George | last post by:
Is there a fast way to transfer an Excel range to an array? Example: Excel range is E2:E300 Dim person() as string Thanks, George
3
8892
by: George | last post by:
Sub ExcelToListBox() Dim xRange As Object Dim ary Dim xValue As String xRange = oXL.Range("A1:A9") 'has letters A-H ary = xRange.value xValue = ary(3, 1) 'xValue = C Me.ListBoxPerson.Items.AddRange(ary)
17
3045
by: John Salerno | last post by:
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...
29
2864
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
8552
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
16
1800
by: lisa.engblom | last post by:
I have two semi related questions... First, I am trying to output a list of strings to a csv file using the csv module. The output file separates each letter of the string with a comma and then puts each string on a separate line. So the code is: import csv output = csv.writer(open('/Python25/working/output.csv', 'a')) a = for elem in range(len(a)):
50
2515
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.
0
1509
by: Matthieu Brucher | last post by:
2008/11/5 L V <somelauw@yahoo.com>: Hi, I don't think the Python developers list is th best list to post this kind of question. What version of Python did you use for this test? Matthieu
0
8466
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
8384
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
8896
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
8810
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
8659
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...
0
7410
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
6211
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
4208
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...
2
2035
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.