how to reverse slice python list

Question:

Would appreciate some help, how do you slice a python list like example below:

a = [1,2,3,4,5,6,7,8]

I want the slice in a loop so output would be:

8,7,6,5,4,3,2,1
8,7,6,5,4,3,2
8,7,6,5,4,3
8,7,6,5,4
8,7,6,5
8,7,6
8,7
8

should be in function like :

    for i in range(len(a)):
        print(a["slice here"])

i’ve tried [-1::-1-i] not sure anymore? thought this would be straightforward ?

Asked By: mac95782

||

Answers:

You are trying to reverse the list and then remove the last number in the list.

a = [1,2,3,4,5,6,7,8]
a.reverse()
for i in range( 1, len(a)):
    print(a[:-i])

if you want without the brackets

a = [1,2,3,4,5,6,7,8]
a.reverse()
for i in range( 1, len(a)):
    print(str(a[:-i])[1:-1])
Answered By: Pw Wolf

Just do it like this friendo, in this case I reverse the list, than I do a reverse range so you can print it out. According to the given index

l = [1,2,3,4,5,6,7,8][::-1]

for i in range(len(l),0,-1):
   print(l[:i])
Answered By: INGl0R1AM0R1

Below code works.

a = [1,2,3,4,5,6,7,8]
for i in range(len(a)):
    print(a[i:len(a)][::-1])

OR

a = [1,2,3,4,5,6,7,8]
for i in range(0,len(a)):
    if i==0:    
        print(a[-1:i:-1]+[a[0]]) 
    else:   
        print(a[-1:i-1:-1])
Answered By: AMISH GUPTA

Try :i-len(a)-1:-1 for your "slice here".

Answered By: Scott Hunter
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.