Inclusive range() in Python

The Python’s built-​in range() is an extremely useful func­tion, but has a little prob­lem: it doesn’t include the right extreme of the range. For exam­ple, a call to range(1, 10) will be eval­u­ated to this a list of num­bers from 1 to 9 (not includ­ing 10):

>>> range(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Today I need for a work a range() func­tion that includes the right extreme, so I had to develop mine. Here it is:

def inclusive_range(start, stop, step=1):
    """
    A range() clone, but this includes the extremes
    """
    l = []
    x = start
    while x <= stop:
        l.append(x)
        x += step
    return l

Of course there are faster imple­men­ta­tions of this func­tion around here (and if you know one, please let me know) and surely this one is not one of the fastest, but it works and that solves my prob­lem right now.

Leave a comment ?

11 Comments.

  1. How fast is:
    def inclusive_range(start, stop, step=1):
    return(range(start, stop+1, step))

    ?

  2. god­damn… this is what hap­pens when coding 8 hours straight on…

  3. You may want to con­sider a sit­u­a­tion with a neg­a­tive step as well, in which case it is just better to add the step (pos­i­tive or neg­a­tive) to the stop:

    def inclusive_range(start, stop, step=1):
    return(range(start, stop+step, step))

    -Chris

  4. Dern lack of pre­view :)

    def inclusive_range(start, stop, step=1):
    return(range(start, stop+step, step))

  5. irange = lambda x,y,z=1: range(x,y+1,z)

  6. @ Com­ments 1 & 2:

    Lol. That’s great — been there.

  7. I think Chris’s def­i­n­i­tion is not quite right. Con­sider these calls:


    range(1, 5, 3) => [1, 4]
    inclusive_range(1, 5, 3) => [1, 4, 7]

    The inclu­sive range shouldn’t include 7, since it is strictly greater than 5.

    I think this is one way to define the inter­face with the same seman­tics as the range() built-​in other than chang­ing the right bound to be inclu­sive:


    def inclusive_range(*args):
    if len(args) == 1:
    start = 0
    stop = args[0]
    step = 1
    elif len(args) == 2:
    (start, stop) = args
    step = 1
    elif len(args) == 3:
    (start, stop, step) = args
    else:
    raise TypeError("Expected 1-3 args, got", len(args))
    if step > 0:
    return range(start, stop + 1, step)
    else:
    return range(start, stop - 1, step)


  8. def inclusive_range(*args):
    numargs = len(args)
    if numargs < 1:
    raise TypeError("irange requires at least one argument.")
    elif numargs == 1:
    stop = args[0];
    start = 0;
    step = 1;
    elif numargs == 2:
    (start,stop) = args
    step = 1
    elif numargs == 3:
    (start,stop,step) = args
    else:
    raise TypeError("irange expected at most 3 argu­ments, got %s" % (str(numargs)))
    i = start
    if step == 0:
    step = 1
    while i <= stop:
    yield i
    i += step


  9. def inclusive_range(start, stop=None, step=1):
    if stop == None:
    start, stop = 0, start

    exten­sion = -1 if step < 0 else 1

    return range(start, stop + exten­sion, step)

    It’ll differ from range() in that a second argu­ment of None will cause it to do a [0..N] range as in one argu­ment. It’ll also throw some­what dif­fer­ent errors if you feed it strings or sim­i­lar, but so do most of the other exam­ples.

    The other code prob­a­bly com­mu­ni­cates better, but this was fun to try to write con­cisely!

  10. Nick’s solu­tion will best serve the pur­pose and behaves exactly like range() of Python. That is, it can be passed 1, 2 or 3 argu­ments just like the range(). Any­thing else would raise an appro­pri­ate excep­tion.

    Exam­ple:
    inclusive_range(25) for range from 0 to 25 inclu­sive with default step of 1.
    inclusive_range(10,25) for range from 10 to 25 inclu­sive with default step of 1.
    inclusive_range(10,25,5) for range from 10 to 25 inclu­sive with a custom step of 5.

    inclusive_​range and inclusive_range(1,10,1,32) will raise excep­tions.

  11. I’d sug­gest that you create an iter­a­tor like this:

    class inclusive_range():
    def __init__(self, *args):
    numargs = len(args)

    if numargs < 1:
    raise TypeError('Inclusive Range requires at least 1 argument')

    elif numargs == 1:
    self.stop = args[0]
    self.start, self.step = 0, 1

    elif numargs == 2:
    (self.start, self.stop) = args
    self.step = 1

    elif numargs == 3:
    (self.start, self.stop, self.step) = args

    else:
    raise TypeError('Inclusive Range expects at the most 3 arguments, got {}'.format(numargs))

    def __iter__(self):
    i = self.start
    while i <= self.stop:
    yield i
    i += self.step

    Then you can use it like an iter­able object like range(). For exam­ple,
    for i in inclusive_range(5,100,5): print(i, end = ' ')

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">