Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list subtraction
#1
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?
Reply
#2
You cannot access aa[i + 1] when i has value len(aa) - 1.
Reply
#3
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?
Reply
#4
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]
>>> 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  numpy subtraction of two arrays devenuro 1 11,733 Sep-24-2018, 12:55 AM
Last Post: Mekire
  How to do matrix subtraction SriRajesh 0 2,728 Jun-01-2018, 02:00 PM
Last Post: SriRajesh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020