Python Forum

Full Version: list subtraction
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I separated a list into sublists and now I want to subtract the second list from the first one, the third from the second and so on.
The following code
my_list = [1,2,4,5,6,9,0,34,56,89,31,42,5]
nn = 3
aa=([my_list[i:i + nn] for i in range(0, len(my_list), nn)])
print(aa)

for i in range(len(aa)):
    print(([int(x) - int(y) for x, y in zip(aa[i+1],aa[i])]))
outputs the right answer, but together with the following error:

Error:
Traceback (most recent call last): [[1, 2, 4], [5, 6, 9], [0, 34, 56], [89, 31, 42], [5]] [4, 4, 5] print(([int(x) - int(y) for x, y in zip(aa[i+1],aa[i])])) [-5, 28, 47] IndexError: list index out of range [89, -3, -14] [-84] Process finished with exit code 1
What should I do to obtain the same answer without the error message? What exactly is causing it?
You cannot access aa[i + 1] when i has value len(aa) - 1.
I thought so too, but if I set the range to len(aa)-1, I run into the same problem,
and it still doesn't explain why I get the result I expect anyway. Strange, no?
It works for me
>>> my_list = [1,2,4,5,6,9,0,34,56,89,31,42,5]
>>> nn = 3
>>> aa=([my_list[i:i + nn] for i in range(0, len(my_list), nn)])
>>> print(aa)
[[1, 2, 4], [5, 6, 9], [0, 34, 56], [89, 31, 42], [5]]
>>> for i in range(len(aa)-1):
...     print(([int(x) - int(y) for x, y in zip(aa[i+1],aa[i])]))
... 
[4, 4, 5]
[-5, 28, 47]
[89, -3, -14]
[-84]
>>>