Problem with Python xrange

Konstantin Veretennicov kveretennicov at yahoo.com
Tue Jun 8 11:09:27 EDT 2004


"Christian Neumann" <mail at neumann-rosenheim.de> wrote in message news:<mailman.631.1086545766.6949.python-list at 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.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



More information about the Python-list mailing list