I'd like to slice a list in reverse but shift the end-index by 1 each time to include more elements. How to include the number at index 0?
x = [2, 5, 8, 10]
for endIdx in [3, 2, 1, 0]:
print(x[3: endIdx - 1: -1])
# output:
# [10]
# [10, 8]
# [10, 8, 5]
# []
# last output is not [10, 8, 5, 2] as desired.
To include the number at index 0, I can do
x = [2, 5, 8, 10]
for endIdx in [3, 2, 1, 0]:
if endIdx != 0:
print(x[3: endIdx - 1: -1])
else:
print(x[3::-1])
but clearly this requires more code just to deal with this edge case. Is there a more elegant solution?