Problem with Python xrange

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Christian Neumann

    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




  • Adonis

    #2
    Re: Problem with Python xrange

    "Christian Neumann" <mail@neumann-rosenheim.de> wrote in message
    news:mailman.63 1.1086545766.69 49.python-list@python.org ...[color=blue]
    > 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[/color]

    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.[color=blue][color=green][color=darkred]
    >>> x = range(10)
    >>> y = xrange(10)
    >>> type(x)[/color][/color][/color]
    <type 'list'>[color=blue][color=green][color=darkred]
    >>> type(y)[/color][/color][/color]
    <type 'xrange'>[color=blue][color=green][color=darkred]
    >>> help(xrange)[/color][/color][/color]
    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.


    Comment

    • Diez B. Roggisch

      #3
      Re: Problem with Python xrange

      Christian Neumann wrote:
      [color=blue]
      > x[1:4] ## It should be return an xrange object with length 3
      > Is this really a bug?[/color]

      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

      Comment

      • r holland

        #4
        Re: Problem with Python xrange

        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.

        Comment

        • r holland

          #5
          Re: Problem with Python xrange

          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 >.

          Comment

          • Konstantin Veretennicov

            #6
            Re: Problem with Python xrange

            "Christian Neumann" <mail@neumann-rosenheim.de> wrote in message news:<mailman.6 31.1086545766.6 949.python-list@python.org >...[color=blue]
            > 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
            >[/color]

            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:
            [color=blue][color=green][color=darkred]
            >>> from itertools import islice
            >>> x = xrange(2, 11, 2)
            >>> s = islice(x, 1, 4)
            >>> for i in s:[/color][/color][/color]
            .... 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:
            [color=blue][color=green][color=darkred]
            >>> from itertools import islice
            >>> x = xrange(3)
            >>> list(x); list(x)[/color][/color][/color]
            [0, 1, 2]
            [0, 1, 2][color=blue][color=green][color=darkred]
            >>> s = islice(xrange(3 ))
            >>> list(s); list(s)[/color][/color][/color]
            [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

            Comment

            • Peter Otten

              #7
              Re: Problem with Python xrange

              Konstantin Veretennicov wrote:
              [color=blue]
              > 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.[/color]

              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

              Comment

              • Terry Reedy

                #8
                Re: Problem with Python xrange


                "Konstantin Veretennicov" <kveretennicov@ yahoo.com> wrote in message
                news:5155aad2.0 406080709.698cb a47@posting.goo gle.com...[color=blue]
                > 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".[/color]

                It is also slight ambigous. Should the result be a list or another xrange?
                [color=blue]
                > You have at least three alternatives:[/color]

                [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




                Comment

                Working...