2

I have created a function that takes a list of integers and subtracts from left to right to return the final answer. I am not keen on using a count variable to skip through the first loop as it seems wasteful - Is there a better way of doing this in Python?

def subtract(numlist):
''' numlist -> int
    Takes a list of numbers and subtracts from left to right
'''
answer = numlist[0]
count = 0
for n in numlist:

    if count != 0:
        answer -= n

    count += 1
return answer

print(subtract([10,2,4,1]))
Phil
  • 21
  • 2

5 Answers5

2

Just sum everything but the first element, and then subtract:

>>> def subtract(numlist):
...    return numlist[0] - sum(numlist[1:])
...
>>> print(subtract([10,2,4,1]))
3
jterrace
  • 64,866
  • 22
  • 157
  • 202
1

You can use list slicing:

>>> def subtract(numlist):
...     result = numlist[0]
...     for n in numlist[1:]:
...             result -= n
...     return result
... 
>>> subtract(L)
3

We first get the first element in the list, as you've shown, but instead of iterating through the whole list with a counter, we can just slice that first element off and iterate as normal.

TerryA
  • 58,805
  • 11
  • 114
  • 143
1

This particular operation is built in to python2, and available in functools in python3, as reduce:

reduce(...)
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

Hence:

>>> l = [10, 2, 4, 1]
>>> import operator
>>> reduce(operator.sub, l)
3
torek
  • 448,244
  • 59
  • 642
  • 775
0

Instead of using a count variable, you could try for n in numlist[1:]

More on list slicing

Community
  • 1
  • 1
mattr555
  • 27
  • 7
0

You can get an iterator for the list and use that to loop over it:

def subtract(l):
    it = iter(l)
    first = next(it)

    # Since the iterator has advanced past the first element,
    # sum(it) is the sum of the remaining elements
    return first - sum(it)

It's a bit faster than using a slice, since you don't have to copy the list.

user2357112
  • 260,549
  • 28
  • 431
  • 505