Home > Net >  pyhon list reverse slicing excludes 1st item
pyhon list reverse slicing excludes 1st item

Time:12-15

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.

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.

CodePudding user response:

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

CodePudding user response:

You can avoid any checking or slicing by just inverting the list as already suggested.

After defining your list you can do: l.reverse() OR l = l[::-1] (which is the same thing)

For the future, just know that, when slicing lists, the first index is included, but the last isn't. So if you have mylist = [0, 1, 2, 3, 4] doing mylist[1:3] will return [1, 2]

CodePudding user response:

You could use None.

for i in range(s):
    print(l[: i-1 if i else None : -1])
  • Related