How to subtract a number by the next number?
Solution 1:
zip
is appropriate here, instead of enumerate
. Simply zip a_list
with a_list[1:]
(so that you can "see" two consecutive elements) and find differences.
new_list = [i-j for i, j in zip(a_list, a_list[1:])]
The reason enumerate
doesn't work with your implementation is that you want to index an integer in a_list
by num[i+1]
which is nonsensical.
If you absolutely want to use enumerate
, one important thing is to ensure that you don't want get an IndexError, i.e. you don't want to index beyond the list. One way to ensure that doesn't happen is to only enumerate until a_list[:-1]
. Then make sure you index a_list
(and not num
) and you're good to go.
new_list = []
for i, num in enumerate(a_list[:-1]):
new_num = num - a_list[i+1]
new_list.append(new_num)
Output:
[2, 11, 4, 4, 2, 1]