Arithmetic sequences in Python

Roberto De Almeida ralmeida at gmail.com
Thu Jan 19 13:31:11 EST 2006


How about this hack:

>>> import types
>>> class lazy_range(object):
...     def __getitem__(self, l):
...         start = l[0]
...
...         if isinstance(l[1], types.EllipsisType):
...             step = 1
...             if len(l) > 2:
...                 stop = l[2]
...             else:
...                 stop = None
...         else:
...             step = l[1] - l[0]
...             if len(l) > 3:
...                 stop = l[3]
...             else:
...                 stop = None
...
...         for i in xrange(start, stop+1, step):
...             yield i
>>>
>>> l = lazy_range()
>>> print [i for i in l[1,3,...,10]]
[1, 3, 5, 7, 9]
>>> print [i for i in l[1,...,10]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]




More information about the Python-list mailing list