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 ?
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])
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])
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])
Try :i-len(a)-1:-1
for your "slice here"
.
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 ?
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])
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])
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])
Try :i-len(a)-1:-1
for your "slice here"
.