Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does range(start, end) not include end?

Tags:

python

range

>>> range(1,11) 

gives you

[1,2,3,4,5,6,7,8,9,10] 

Why not 1-11?

Did they just decide to do it like that at random or does it have some value I am not seeing?

like image 902
MetaGuru Avatar asked Dec 21 '10 22:12

MetaGuru


People also ask

Does range include the last number?

Inclusive range By default, The range(n) is exclusive, so it doesn't include the last number in the result. It creates the sequence of numbers from start to stop -1 . For example, range(5) will produce [0, 1, 2, 3, 4] . The result contains numbers from 0 to up to 5 but not five.

Is range inclusive or exclusive?

The exclusive type of range is most commonly used and most frequently known by the name "Range." It is obtained by differencing the highest and the smallest value of the data set. The inclusive type of range is obtained by adding 1 to the difference of the data's maximum and minimum value.

Does range include 0?

The range is also all real numbers except zero. You can see that there is some point on the curve for every y -value except y=0 . Domains can also be explicitly specified, if there are values for which the function could be defined, but which we don't want to consider for some reason.

Does range include 0 Python?

Definition and Usage. The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.


1 Answers

Because it's more common to call range(0, 10) which returns [0,1,2,3,4,5,6,7,8,9] which contains 10 elements which equals len(range(0, 10)). Remember that programmers prefer 0-based indexing.

Also, consider the following common code snippet:

for i in range(len(li)):     pass 

Could you see that if range() went up to exactly len(li) that this would be problematic? The programmer would need to explicitly subtract 1. This also follows the common trend of programmers preferring for(int i = 0; i < 10; i++) over for(int i = 0; i <= 9; i++).

If you are calling range with a start of 1 frequently, you might want to define your own function:

>>> def range1(start, end): ...     return range(start, end+1) ... >>> range1(1, 10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
like image 52
moinudin Avatar answered Oct 14 '22 22:10

moinudin