Ian Nelson
Ian Nelson

Reputation: 33

Python: How to subtract the first number in a list with the second number

So I've looked everywhere and I cannot find the answer for this anywhere.

So I'm trying to subtract a list of numbers like [1, 2, 3] = -4 cause 1-2-3 = -4.

I was trying to use slices of lists to accomplish this but I just can't figure this out.

Upvotes: 1

Views: 3291

Answers (2)

corn3lius
corn3lius

Reputation: 4985

alternatively you could use the reduce builtin

>>> s = [1,2,3]
>>> reduce(lambda x,y : x-y, s, None)
-4

Upvotes: 0

JkShaw
JkShaw

Reputation: 1947

Assuming length of list > 0:

>>> s = [1, 2, 3]
>>> s[0] - sum(s[1:])
-4

General Case:

if len(s) > 0:
   return s[0] - sum(s[1:])
else:
   return None

Upvotes: 10

Related Questions