Python : what would be the ouput of range(x,y) if

2019-09-21 20:30发布

问题:

Let x and y be two integers :

How range(x,y) such x>y would be considered in Python ?
I tried following code in both python 2.7 and python 3.3:

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.

回答1:

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.



回答2:

The range's signature is

range(start, stop[, step])

range(10, 3) sets start and stop to 10 and 3, respectively, therefore if you will to provide the step argument, you'll need to provide the start argument:

In [1]: range(0, 10, 3) # list(range(0, 10, 3)) in Python3+
Out[1]: [0, 3, 6, 9]

The step's default value is 1 and (quoting the documentation page I linked before)

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

range(10, 3) is empty because r[i] < stop is false from the very beginning (r[0] is 10 + 1*0 = 10 and 10 is greater than 3).



回答3:

range() with just two arguments interprets those arguments as start and stop. From the range() function documentation:

range(stop)
range(start, stop[, step])

Note that [, step] is optional in the second form. By supplying a stop that is smaller or equal to start while leaving step at the default 1, you created an empty range. The documentation includes this case explicitly as one of the examples given:

>>> range(1, 0)
[]

The Python 3 version of the documentation is a little more explicit still:

A range object will be empty if r[0] does not meet the value constraint.

If you wanted to supply a step value, you have to specify the start:

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

Python refuses to guess here; there are legitimate uses for using variables for both the start and stop arguments, where given certain runs of an algorithm the stop value ends up equal or lower than the start; such code expects the range() to be empty in such cases.



标签: python range