I want to traverse a list in a certain arrangement of slices:
l = range(10)
for i in (0,1,2):
print l[i:i + 3]
# [0, 1, 2]
# [1, 2, 3]
# [2, 3, 4]
however when I try to do it from the ending of the list, the case where i = 0
fails
l = range(10)
for i in (0,1,2):
print l[-(i + 3):-i]
# [] // expected: [7, 8, 9]
# [6, 7, 8]
# [5, 6, 7]
I understand why this doesn't work.
l[-1:]
l[-1:None]
both work but
l[-1:0]
retrieves an empty set due to 0
referencing the first element, not the "element after the last element".
However I wonder if there is a solution to implement a straightforward "iterate from x to end" where end
doesn't have to be treated specially in case I actually reach the end.
The examples above are merely examples, I am trying to assign values in NumPy so l[...].reverse()
etc. will not work.
You could use len(l) - i
in place of -i
:
l = range(10)
for i in (0,1,2):
print l[-(i + 3):len(l) - i]
output:
[7, 8, 9]
[6, 7, 8]
[5, 6, 7]
One approach is to do a bit of arithmetic to avoid using negative indexes.
n = len(l)
for i in (0, 1, 2):
j = n - 3 - i;
print l[j: j + 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With