15

I want to iterate over a closed range of integers [a, b] in python, ie. iterating from a to b including both a and b.

I know the following way of doing it:

for i in range(a, b+1):
    do_something(i)

For iterating in the reverse direction (ie. in the order b, b-1, b-2, ..., a), I do the following:

for i in range(b, a-1, -1):
    do_something(i)

I don't like this addition (b+1 in the example) and subtraction (a-1 in the example) to reach the closed end of the range. I find it less readable than the c/c++/Java counterpart (usage of <= in a loop).

Do you have something in python which can be used to iterate between the closed ranges without manual intervention of the boundaries?

krips89
  • 1,683
  • 4
  • 17
  • 32
  • Why do you need this? Actual sequential integers are very rarely needed. Most of the time you are iterating over iterators (in Java/C++ as well). – Pavel Anossov Apr 21 '13 at 19:54
  • 1
    As long as you remember that the end parameter is exclusive (corresponding to `<` or `>` in a for loop), you won't have any trouble adjusting to it. Another way to think about it is that range(a,x)+range(x,b) = range(a,b), which wouldn't be the case if it was inclusive with respect to the end parameter. – Stjepan Bakrac Apr 21 '13 at 19:57
  • You can define your own `range()` function modifying these to achieve this. – Ashwini Chaudhary Apr 21 '13 at 20:02
  • @PavelAnossov, I met with this situation a lot of time when I have an actual need of iterating over a range. – krips89 Apr 21 '13 at 20:06
  • 1
    @AshwiniChaudhary, So no standard, ready to use functions/methodologies like that in python? – krips89 Apr 21 '13 at 20:08
  • @krips89 AFAIK there are no such range functions in python, similar question: http://stackoverflow.com/questions/4504662/why-does-rangestart-end-not-include-end – Ashwini Chaudhary Apr 21 '13 at 20:12
  • @krips89: I was hoping for an actual example. – Pavel Anossov Apr 21 '13 at 20:32

1 Answers1

7

It's a simple matter to define your own function and use it:

def closed_range(start, stop, step=1):
  dir = 1 if (step > 0) else -1
  return range(start, stop + dir, step):

In action:

>>> list(closed_range(1, 10))
0: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(closed_range(1, 10, 2))
1: [1, 3, 5, 7, 9]
>>> list(closed_range(1, 10, 3))
2: [1, 4, 7, 10]
>>> list(closed_range(10, 1, -1))
3: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> list(closed_range(10, 1, -2))
4: [10, 8, 6, 4, 2]

Save to a .py file in \PythonXX\Lib\site-packages and then you can import it for use elsewhere.

bbayles
  • 4,389
  • 1
  • 26
  • 34
  • 3
    Yeah its simple to write some function like that, but I was looking if something was available in the python library itself and if not why they thought it was unnecessary. – krips89 Apr 23 '13 at 04:34