Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic in Python slicing, end behaviour

Tags:

python

slice

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.

like image 400
Nils Werner Avatar asked Feb 10 '23 16:02

Nils Werner


2 Answers

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]
like image 59
Janne Karila Avatar answered Feb 13 '23 06:02

Janne Karila


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]
like image 21
FMc Avatar answered Feb 13 '23 06:02

FMc