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