Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
why is range() int only
#1
why is range() int only? why did they not allow it to work with float and decimal ... at least with all args the same type?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
I guess the reason is historical. Also it avoids type checking in a heavily used function. numpy.arange() supports several data types.
Reply
#3
Because range is used for indexing and if you need to address an element in a sequence, you need integers.
But you've all tools to build your own range:

def arange(start_or_end, end=None, step=1):
    if end is None:
        start_or_end, end = 0, start_or_end

    value = start_or_end

    while value < end:
        yield value
        value += step
Testing with Decimal:
from decimal import Decimal


for dec in arange(Decimal(0), Decimal(5), Decimal("0.25")):
    print(dec)
Output:
0 0.25 0.50 0.75 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 3.00 3.25 3.50 3.75 4.00 4.25 4.50 4.75
Testing with Fraction:
from fractions import Fraction


for frac in arange(Fraction(0), Fraction(5), Fraction(1, 3)):
    print(frac)
Output:
0 1/3 2/3 1 4/3 5/3 2 7/3 8/3 3 10/3 11/3 4 13/3 14/3
Testing with float:
from decimal import Decimal


for real in arange(0, 5, 0.25):
    print(real)
Output:
0 0.25 0.5 0.75 1.0 1.25 1.5 1.75 2.0 2.25 2.5 2.75 3.0 3.25 3.5 3.75 4.0 4.25 4.5 4.75
Gribouillis and Skaperen like this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
the indexing use case being so dominant does not rule out other use cases. but a concise efficient implementation in C might be the reason. it does type check, and other checks. if it is in C then a type check is probably essential to avoid memory corruption that C is infamous for. i played around with implementing my own. it does reverse decrements, too. i have only tested floats. but it looks like numpy will be in my float use case. or i might scale the ints.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020