Turn slice into range

There’s an easier way to do this (at least in 3.4, I don’t have 3.3 at the moment, and I don’t see it in the changelog).

Assuming your class already has a known length you can just slice a range of that size:

>>> range(10)[1:5:2]
range(1, 5, 2)
>>> list(range(10)[1:5:2])
[1, 3]

If you don’t know the length a priori you’ll have to do:

>>> class A:
    def __getitem__(self, item):
        if isinstance(item, slice):
            return list(range(item.stop)[item])
>>> a = A()
>>> a[1:5:2]
[1, 3]
>>> a[1:5]
[1, 2, 3, 4]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)