Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pyhon list reverse slicing excludes 1st item

I would like to go through on a list in reverse order using slices of the list, but I am having trouble to have the 1st (index 0) item of the list on the output.

l=[0,1,2,3,4,5,6]
s=len(l)

for i in range(s):
    print(l[s:i:-1])

The output is missing the 1st item of the list:

 [6, 5, 4, 3, 2, 1]
 [6, 5, 4, 3, 2]
 [6, 5, 4, 3]
 [6, 5, 4]
 [6, 5]
 [6]
 []

It looks like just a shifting problem, but i-1 doesn’t work as an index when i=0.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The only solution so far I could figure out is ugly:

l=[0,1,2,3,4,5,6]
s=len(l)

for i in range(s):
    if i == 0:
        print(l[s::-1])
    else:
        print(l[s:i-1:-1])

Output (what I really wanted):

 [6, 5, 4, 3, 2, 1, 0]
 [6, 5, 4, 3, 2, 1]
 [6, 5, 4, 3, 2]
 [6, 5, 4, 3]
 [6, 5, 4]
 [6, 5]
 [6]

For me it looks like a design failure in python as in a reverse slicing there is no other way to have the 1st item of the list then leaving the field empty, what is a problem when you have a variable there… Tell me how to do it better.

>Solution :

You could slice it in reverse then iterate through the reversed slice

l=[0,1,2,3,4,5,6]
s=len(l)

for i in range(s):
    print(l[::-1][0:s-i])
    
print(l)

and the original list wouldn’t be updated

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading