2

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
Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
IICatzII
  • 25
  • 1
  • 3

4 Answers4

9

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.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
2

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:])
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
2

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]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

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:]))
prudhvi Indana
  • 789
  • 7
  • 19