3

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
0

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Any reason to prefer the lambda over operator.sub?
None - you can use operator.sub, if you wish. I guess, it can even be slightly more efficient.
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:])

3 Comments

That would give a wrong result, though.
@vaultah, fixed.
Okay, why not ListOfNumbers[0] - sum(ListOfNumbers[1:]) then?
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]

Comments

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:]))

2 Comments

might want to properly format this?
formatted the code @aws_apprentice

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.