Closed-range iteration [a, b] in python

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

I know the following way:

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

To iterate in the opposite direction (i.e. in the order of b, b-1, b-2, ..., a), I do the following:

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

I do not like this addition (b + 1 in the example) and subtraction (a-1 in the example) to achieve the closed end of the range. I find it less readable than a c / C ++ / Java copy (using <= in a loop).

Do you have something in python that can be used to repeat between closed ranges without manual border intervention?

+4
source share
1 answer

Just 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 the .py file in the \ PythonXX \ Lib \ site folders, and then you can import it for use elsewhere.

+3
source

All Articles