Iterative sliced indexing (python) starting form the end : how to avoid "-0" to be equal to "0"?

Viewed 51

I have a list (actually a pandas.DataFrame, but let's make it simple), let's say:

a = list(range(10))

I have to iterate on it and extract at each loop all the element from the beginning up to a "moving end". I want the whole list at the first iteration, drop the last element at the second iteration, drop the two last elements at third...and so on.

It seemed easy to code:

for i in range(5) :
    print(i,a[:-i])

In fact this code works fine from "1" and later. But for i=0 I get an empty list, while I would like to get the full list.

I understand than "-0" is equal to "0" and that's why I am having this behaviour...but is there anything I could do about that?

Thanks!

2 Answers

I finally found out how to deal with it, by adding to the negative indexed end the list length :

for i in range(5) :
    print(i,a[:len(a)-i])

This modification produces the whole list at the first iteration (desired result).

You could calculate the ending index explicitly:

for i in range(5):
    print(i, a[: len(a) - i])

Or replace the end index with None when at zero:

for i in range(5):
    print(i, a[: -i or None])
Related