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!

2
  • 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. Commented Mar 18, 2021 at 20:51
  • you can use cycle for continued list. Commented Mar 18, 2021 at 20:54

2 Answers 2

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]) 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.