Search code examples
pythonlistsubtraction

subtract nth item from list from nth item in different list in Python


I want to modify this code:

def differenceinX(list1,list2):
    answer=[n1 - n2 for (n1, n2) in zip(list1, list2)]
    return answer

to something like:

def differenceinX[x](list1[x],list2[x]):
    answer=[n1 - n2 for (n1, n2) in zip(list1[x], list2[x])]
    return answer

I have 2 lists (23,24,26), (24,24,25) and I want to be able to subtract the 1st item in the first list from the 1st item in the second list. I get error message 'invalid syntax'


Solution

  • I think this will do what you are looking for,

    def differenceinX(list1,list2, index):
      answer = list1[index] - list2[index]
      return answer