range and xrange

Delaney, Timothy tdelaney at avaya.com
Tue Jun 12 20:34:01 EDT 2001


Just a little bit of fun code ... which gets rid of range(len(list)) bits
everywhere ... however, it is slightly slower as it has to trap an exception
to work.

If you wish to be more explicit, you can import __builtin__ and have the
default value for the range/xrange functions be
__builtin__.__dict__['range'] and __builtin__.__dict__['xrange']
respectively - you can also assign these to __builtin__ to make them work
everywhere.

def range (start, stop=None, step=1, range=range):
    """"""

    start2 = start
    stop2 = stop

    if stop is None:
        stop2 = start
        start2 = 0

    try:
        return range(start2, stop2, step)
    except TypeError:
        assert stop is None
        return range(len(start))

def xrange (start, stop=None, step=1, xrange=xrange):
    """"""

    start2 = start
    stop2 = stop

    if stop is None:
        stop2 = start
        start2 = 0

    try:
        return xrange(start2, stop2, step)
    except TypeError:
        assert stop is None
        return xrange(len(start))

a = [5, 'a', 'Hello, world!']
b = range(a)
c = xrange(4, 6)
d = xrange(b)
e = range(c)

print a
print b
print c
print d
print e
print range(d, 2)

Tim Delaney
Avaya Australia
+61 2 9352 9079




More information about the Python-list mailing list