Python Forum
itertool islice why no negative values ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: itertool islice why no negative values ? (/thread-23997.html)



itertool islice why no negative values ? - voidptr - Jan-26-2020

About itertool islice.

Why islice doesn't support negative values ?

( I realized than negative index need oftn the len() of something, it might need a complete generation of the list to get this, but for some generators and some different iterators might not ... )

Here my snippet, maybe someone can do better :)
(of course here im using a range, instead of some generators or iterators)


import itertools as it

def xislice(iterable, *args):
    #xislice(coll,stop)
    #xislice(coll,start,stop,[step])
    #handle negative args

    sz = len(args)
    if sz == 0:
        start = 0
        stop = len(iterable)
        step = 1
    elif sz == 1:
        start = 0
        stop = args[0] if args[0] != None else len(iterable)
        step = 1
    elif sz == 2:
        start = args[0] if args[0] != None else 0
        stop = args[1] if args[1] != None else len(iterable)
        step = 1
    else:
        start = args[0] if args[0] != None else 0
        stop = args[1] if args[1] != None else len(iterable)
        step = args[2] if args[2] != None else 1

    for x in range(start, stop, step):
        yield iterable[x]



xx = list(range(0,20))
yy = [x for x in it.islice(xx,1,None,2)]
print(yy)

yy = [x for x in xislice(xx,1,None,2)]
print(yy)

yy = [x for x in xislice(xx,15,-1,-2)]
print(yy)

#yy = [x for x in it.islice(xx,15,-1,-2)]



RE: itertool islice why no negative values ? - Gribouillis - Jan-27-2020

You might want to compare this with more_itertools.islice_extended()


RE: itertool islice why no negative values ? - voidptr - Jan-27-2020

Interesting, I didn't had the time to search for others implementations, but I will .
Thanks for the pointers :)