473,786 Members | 2,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2582
"Christian Neumann" <ma**@neumann-rosenheim.de> wrote in message
news:ma******** *************** **************@ python.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******* *************** *************** @python.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.islic e:
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(o bject):
def __getitem__(sel f, index):
if isinstance( index, slice):
if index.step is None:
return xrange(index.st art, index.stop)
return xrange(index.st art, 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.goo gle.com...
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
972
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
2510
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 actually taking place at places where I didn't expect it. after I have created a lookup-table-dictionary with encodings like {'d':'0110', 'e':'01' etc} to encode the original text like this:
30
3479
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, is that dict comprehensions don't gain you >> much at all over the dict() constructor plus a generator expression, >> e.g.: >> dict((i, chr(65+i)) for i in range(4)) > > Sure, but the same holds for list comprehensions: list(i*i for i in
18
1502
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
1206
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, xrange(3000)))" 100 loops, best of 3: 3.6 msec per loop
10
3978
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 than 'while'? C: for(i=0; i<length; i++) python: while i < length:
18
2976
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
3807
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 let me down, but it has proved surprisingly slow on one puzzle. The puzzle is: p is the perimeter of a right angle triangle with integral length sides, {a,b,c}. which value of p < 1000, is the number of solutions {a,b,c} maximised? Here's my...
0
1719
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 helps Edwin
0
9647
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
9496
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
10164
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
10110
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
9961
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
7512
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
6745
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
5397
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
4066
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

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.