472,364 Members | 1,554 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Problem with Python xrange

Hello,

i have a problem with the built-in function xrange(). Could you by any
chance be able to help?

I use Python 2.3.4 (final) and i think there is a bug in the built-in
function xrange().

An example is:

x = xrange(2, 11, 2) ## [2, 4, 6, 8, 10]

I get an TypeError if i use it with SliceType:

x[1:4] ## It should be return an xrange object with length 3

Here is the error message:

"TypeError: sequence index must be integer".

Is this really a bug?

Sincerely yours,

Christian Neumann


Jul 18 '05 #1
7 2511
"Christian Neumann" <ma**@neumann-rosenheim.de> wrote in message
news:ma*************************************@pytho n.org...
Hello,

i have a problem with the built-in function xrange(). Could you by any
chance be able to help?

I use Python 2.3.4 (final) and i think there is a bug in the built-in
function xrange().

An example is:

x = xrange(2, 11, 2) ## [2, 4, 6, 8, 10]

I get an TypeError if i use it with SliceType:

x[1:4] ## It should be return an xrange object with length 3

Here is the error message:

"TypeError: sequence index must be integer".

Is this really a bug?

Sincerely yours,

Christian Neumann


Not a bug...

Adonis

Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
x = range(10)
y = xrange(10)
type(x) <type 'list'> type(y) <type 'xrange'> help(xrange)

Help on class xrange in module __builtin__:

class xrange(object)
| xrange([start,] stop[, step]) -> xrange object
|
| Like range(), but instead of returning a list, returns an object that
| generates the numbers in the range on demand. For looping, this is
| slightly faster than range() and more memory efficient.
Jul 18 '05 #2
Christian Neumann wrote:
x[1:4] ## It should be return an xrange object with length 3
Is this really a bug?


No. xrange doesn't create an actual sequence you can slice, instead it
creates an iterable object usable in for ... in ... statements.

The reason is that its much more memory-consuming to create a list if all
you are interested in are only the generated indices.

Use range, if you really want a list.
--
Regards,

Diez B. Roggisch
Jul 18 '05 #3
xrange is a special object intended for operations like looping

try this:

a=xrange(10)
b=range(10)

if you do:

type(a)
type(b)
you'll see that a is 'xrange' and b is a 'list'
if you do:
dir(a)
dir(b)

you'll see that a has all of the list methods (which includes slicing)
whereas b has none.

xrange is a generator object so slicing is not relevant, although
you could assemble a list from the generator using append,
that could then be sliced.
Jul 18 '05 #4
correction to previous post

if you do:
dir(a)
dir(b)

you'll see that <a has none of the list methods (which includes slicing)
whereas b has all of them >.
Jul 18 '05 #5
"Christian Neumann" <ma**@neumann-rosenheim.de> wrote in message news:<ma*************************************@pyth on.org>...
Hello,

i have a problem with the built-in function xrange(). Could you by any
chance be able to help?

I use Python 2.3.4 (final) and i think there is a bug in the built-in
function xrange().

An example is:

x xrange(2, 11, 2) ## [2, 4, 6, 8, 10]

I get an TypeError if i use it with SliceType:

x[1:4] ## It should be return an xrange object with length 3


As other posters have pointed out, slicing xrange object doesn't yield
appropriate x(sub)range but raises exception instead. According to PEP
260 xrange slicing is a "rarely used behavior".

You have at least three alternatives:

1) Obvious.

Forget about xrange() and use range() when you need slicing :)
Especially if you can happily trade speed and memory efficiency for
ability to slice.

2) Quick and dirty.

Use itertools.islice:
from itertools import islice
x = xrange(2, 11, 2)
s = islice(x, 1, 4)
for i in s: .... print i,
....
4 6 8

There are subtleties: islice and xrange objects behave slightly
differently.
For instance, you can iterate many times over xrange items, but only
once over islice items:
from itertools import islice
x = xrange(3)
list(x); list(x) [0, 1, 2]
[0, 1, 2] s = islice(xrange(3))
list(s); list(s)

[0, 1, 2]
[]

3) Involved.

Write a class implementing the behaviour you need. You'll want to
implement xrange interface and slicing protocol. It's not possible to
subclass xrange (yet?), so you'll have to delegate.

BTW, such class may already exist, but I'm too lazy to search...

- kv
Jul 18 '05 #6
Konstantin Veretennicov wrote:
Write a class implementing the behaviour you need. You'll want to
implement xrange interface and slicing protocol. It's not possible to
subclass xrange (yet?), so you'll have to delegate.


class XRangeFactory(object):
def __getitem__(self, index):
if isinstance( index, slice):
if index.step is None:
return xrange(index.start, index.stop)
return xrange(index.start, index.stop, index.step)
return xrange(index)

makeRange = XRangeFactory()
assert list(makeRange[5]) == range(5)
assert list(makeRange[7:11]) == range(7, 11)
assert list(makeRange[7:19:2]) == range(7, 19, 2)

Peter

Jul 18 '05 #7

"Konstantin Veretennicov" <kv***********@yahoo.com> wrote in message
news:51**************************@posting.google.c om...
As other posters have pointed out, slicing xrange object doesn't yield
appropriate x(sub)range but raises exception instead. According to PEP
260 xrange slicing is a "rarely used behavior".
It is also slight ambigous. Should the result be a list or another xrange?
You have at least three alternatives:


[snipped]

add

4) Use range or xrange directly to get the list or xrange you want. Of
course, you have to know the start, stop, and step values, or use the
deprecated attributes of the original xrange.

Terry J. Reedy


Jul 18 '05 #8

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

Similar topics

0
by: Christian Neumann | last post by:
Hello Robert! Sorry. It was my mistake! I read over this: "They don't support slicing" Thank you very much indeed! Christian Neumann
15
by: Guyon Morée | last post by:
Hi all, I am working on a Huffman encoding exercise, but it is kinda slow. This is not a big problem, I do this to educate myself :) So I started profiling the code and the slowdown was...
30
by: Steven Bethard | last post by:
George Sakkis wrote: > "Steven Bethard" <steven.bethard@gmail.com> wrote: >> Dict comprehensions were recently rejected: >> http://www.python.org/peps/pep-0274.html >> The reason, of course,...
18
by: KraftDiner | last post by:
I'm porting a routing from C++ to python. There is a complex for loop that I don't know how to code in python for (i = nPoints-1, j = 0; j < nPoints; i = j, j++) Thanks.
4
by: Giovanni Bajo | last post by:
Hello, I found this strange: python -mtimeit "sum(int(L) for L in xrange(3000))" 100 loops, best of 3: 5.04 msec per loop python -mtimeit "import itertools; sum(itertools.imap(int,...
10
by: Putty | last post by:
In C and C++ and Java, the 'for' statement is a shortcut to make very concise loops. In python, 'for' iterates over elements in a sequence. Is there a way to do this in python that's more concise...
18
by: Marko.Cain.23 | last post by:
Hi, I create a dictionary like this myDict = {} and I add entry like this: myDict = 1 but how can I empty the whole dictionary? Thank you.
25
by: jwrweatherley | last post by:
I'm pretty new to python, but am very happy with it. As well as using it at work I've been using it to solve various puzzles on the Project Euler site - http://projecteuler.net. So far it has not...
0
by: Edwin.Madari | last post by:
-----Original Message----- statement prepared first and executed many times with exectemany - db API http://www.python.org/dev/peps/pep-0249/ inline statemets can be exeucuted only. hope that...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.

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.