May-18-2019, 06:25 AM
I have no idea how len of range is implemented, but wouldn't be surprised that something along those lines:
EDIT: This question intrigued me, so I went to github to check from rangeobject.c how len of range determined. My knowledge of C is next to none, but:
>>> len(range(6,2**60,3)) 384307168202282324 >>> (2**60 - 6) / 3 3.843071682022823e+17However, from documentation of range I can read:
Quote:The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.
Ranges containing absolute values larger than sys.maxsize are permitted but some features (such as len()) may raise OverflowError.
The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).
EDIT: This question intrigued me, so I went to github to check from rangeobject.c how len of range determined. My knowledge of C is next to none, but:
/* Return number of items in range (lo, hi, step). step != 0 * required. The result always fits in an unsigned long. */ static unsigned long get_len_of_range(long lo, long hi, long step) { /* ------------------------------------------------------------- If step > 0 and lo >= hi, or step < 0 and lo <= hi, the range is empty. Else for step > 0, if n values are in the range, the last one is lo + (n-1)*step, which must be <= hi-1. Rearranging, n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so the RHS is non-negative and so truncation is the same as the floor. Letting M be the largest positive long, the worst case for the RHS numerator is hi=M, lo=-M-1, and then hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough precision to compute the RHS exactly. The analysis for step < 0 is similar. ---------------------------------------------------------------*/ assert(step != 0); if (step > 0 && lo < hi) return 1UL + (hi - 1UL - lo) / step; else if (step < 0 && lo > hi) return 1UL + (lo - 1UL - hi) / (0UL - step); else return 0UL; }
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.