2

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!

Songio
  • 325
  • 1
  • 15
  • Sorry, but it just doesn't that work that way. You can do the moving end up through [:-1], and then you have to do the whole list separately. – Tim Roberts Mar 18 '21 at 20:51
  • you can use [cycle](https://docs.python.org/3/library/itertools.html#itertools.cycle) for continued list. – Nilesh Mar 18 '21 at 20:54

2 Answers2

1

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).

Songio
  • 325
  • 1
  • 15
1

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])
ilkkachu
  • 6,221
  • 16
  • 30