Inclusive range() in Python
March 6th, 2008
The Python’s built-in range() is an extremely useful function, but has a little problem: it doesn’t include the right extreme of the range. For example, a call to range(1, 10) will be evaluated to this a list of numbers from 1 to 9 (not including 10):
>>> range(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Today I need for a work a range() function 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 implementations of this function 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 problem right now.
How fast is:
def inclusive_range(start, stop, step=1):
return(range(start, stop+1, step))
?
Comment by Xubuntix — March 7th, 2008 at 0:10
goddamn… this is what happens when coding 8 hours straight on…
Comment by Giuliani Vito, Ivan — March 7th, 2008 at 0:41
You may want to consider a situation with a negative step as well, in which case it is just better to add the step (positive or negative) to the stop:
def inclusive_range(start, stop, step=1):
return(range(start, stop+step, step))
-Chris
Comment by Chris Brinker — April 22nd, 2008 at 22:20
Dern lack of preview :)
def inclusive_range(start, stop, step=1):
return(range(start, stop+step, step))
Comment by Chris Brinker — April 22nd, 2008 at 22:21
irange = lambda x,y,z=1: range(x,y+1,z)
Comment by Wes Turner — June 5th, 2008 at 6:54
@ Comments 1 & 2:
Lol. That’s great — been there.
Comment by Kenny Katzgrau — August 16th, 2008 at 16:17
I think Chris’s definition is not quite right. Consider these calls:
range(1, 5, 3) => [1, 4]
inclusive_range(1, 5, 3) => [1, 4, 7]
The inclusive range shouldn’t include 7, since it is strictly greater than 5.
I think this is one way to define the interface with the same semantics as the range() built-in other than changing the right bound to be inclusive:
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)
Comment by Jon — June 19th, 2009 at 21:16