What would be the output of range(x, y) if x > y?

Issue

Let x and y be two integers:

How would range(x, y) if x > y be considered in Python?

I tried following code:

for i in range(10, 3):
    print(i)

I thought range(10, 3) should be considered as the list [0, 3, 6, 9], but this portion of code isn’t rendering anything.

Solution

You have two options:

  1. rearrange the input values,

    range(0, 10, 3)     # => (0, 3, 6, 9)
    
  2. write a wrapper function which rearranges them for you:

    def safe_range(a, b):
        return range(0, max(a,b), min(a,b))
    
    safe_range(3, 10)   # => (0, 3, 6, 9)
    

Edit: after thinking about it a bit more, I see; you were trying to do something like

range({start=0,} stop, step)

but if you only give two values there is no way to tell the difference between that and

range(start, stop, {step=1})

To resolve this ambiguity, Python syntax demands that default-value parameters can only appear after all positional parameters – that is, the second example is valid Python, the first isn’t.

Answered By – Hugh Bothwell

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.