1 # Example of a generator: re-implement the built-in range function
2 # without actually constructing the list of values. (It turns out
3 # that the built-in function is about 20 times faster -- that's why
7 # Wrapper function to emulate the complicated range() arguments
11 start
, stop
, step
= 0, a
[0], 1
18 raise TypeError, 'range() needs 1-3 arguments'
19 return Range(start
, stop
, step
)
22 # Class implementing a range object.
23 # To the user the instances feel like immutable sequences
24 # (and you can't concatenate or slice them)
28 # initialization -- should be called only by range() above
29 def __init__(self
, start
, stop
, step
):
31 raise ValueError, 'range() called with zero step'
35 self
.len = max(0, int((self
.stop
- self
.start
) / self
.step
))
37 # implement `x` and is also used by print x
39 return 'range' + `self
.start
, self
.stop
, self
.step`
46 def __getitem__(self
, i
):
48 return self
.start
+ self
.step
* i
50 raise IndexError, 'range[i] index out of range'
56 import time
, __builtin__
57 print range(10), range(-10, 10), range(0, 10, 2)
58 for i
in range(100, -100, -10): print i
,
64 for i
in __builtin__
.range(1000):
67 print t2
-t1
, 'sec (class)'
68 print t3
-t2
, 'sec (built-in)'