On 16 Feb 2007 07:30:15 -0800, stdazi <[EMAIL PROTECTED]> 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 >
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): .... -- http://mail.python.org/mailman/listinfo/python-list