Writing a function that alternates plus and minus signs between list indices

def alternate(l):
  return sum(l[::2]) - sum(l[1::2])

Take the sum of all the even indexed elements and subtract the sum of all the odd indexed elements. Empty lists sum to 0 so it coincidently handles lists of length 0 or 1 without code specifically for those cases.

References:


Not using fancy modules or operators since you are learning Python.

>>> mylist = range(2,20,3)
>>> mylist
[2, 5, 8, 11, 14, 17]
>>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
-9
>>>

How it works?

>>> mylist = range(2,20,3)
>>> mylist
[2, 5, 8, 11, 14, 17]

enumerate(mylist, 1) - returns each item in the list and its index in the list starting from 1

If the index is odd, then add the item. If the index is even add the negative of the item.

if i%2:
  return item
else:
  return -1*item

Add everything using sum bulitin.

>>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
-9
>>>