What I want to do is subtract all the items in that list by order:
>>> ListOfNumbers = [1,2,3,4,5,6,7,8,9,10]
>>> 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 # should be computed
-53
What I want to do is subtract all the items in that list by order:
>>> ListOfNumbers = [1,2,3,4,5,6,7,8,9,10]
>>> 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 # should be computed
-53
You could use the reduce()
function:
>>> from functools import reduce
>>> lst = [1,2,3,4,5,6,7,8,9,10]
>>> reduce(lambda x, y: x - y, lst)
-53
Or using operator.sub
instead of the lambda
:
>>> import operator
>>> reduce(operator.sub, lst)
-53
Note that in Python 2.x reduce()
is a built-in, so you don't need to import it.
You can iterate through the array and subtract:
result = ListOfNumbers[0]
for n in ListOfNumbers[1:]:
result -= n
Or, as vaultah pointed out:
result = ListOfNumbers[0] - sum(ListOfNumbers[1:])
With itertools.accumulate
and operator.sub
functions:
import itertools, operator
l = [1,2,3,4,5,6,7,8,9,10]
print(list(itertools.accumulate(l, operator.sub))[-1]) # -53
This not pretends to be better than posted functools.reduce()
solution, but gives an additional feature - intermediate subtraction results for each pair (the 1st item stays as starting point):
[1, -1, -4, -8, -13, -19, -26, -34, -43, -53]
Yet another way of doing it, assuming items as input list.
if len(items) == 0:
print(0)
elif len(items) == 1:
print(items[0])
else:
print(items[0] - sum(items[1:]))