0
list1=[a,b,c,d]
list2=[d,e,f,g]

I want a list3 which should look like:

list3=[a-d,b-e,c-f,d-g]

Please tell me how to do this in a loop as my list1 and list2 have many entities. list1 and list2 contain strings. For example:

list1=['cat','dog']
list2=['dog','cat']
list3=['cat-dog','dog-cat']
RMPR
  • 3,368
  • 4
  • 19
  • 31
Giki
  • 27
  • 6

2 Answers2

4

With zip you can put two lists together and iterate over them simultaneously.

list1=[a,b,c,d]
list2=[d,e,f,g]
list3 = [x-y for x,y in zip(list1,list2)]

EDIT: I answered with the preassumption that you had only integers in your list, if you want to do the same for strings you can do this:

list1 = ["a", "b", "c", "d"]
list2 = ["d", "e", "f", "g"]
list3 = ["-".join([x, y]) for x, y in zip(list1, list2)]
Farhood ET
  • 1,432
  • 15
  • 32
  • Hi I have edited my question a bit please check it out. I am getting an error TypeError Traceback (most recent call last) in ----> 1 list3 = [x-y for x,y in zip(list1,list2)] in (.0) ----> 1 list3 = [x-y for x,y in zip(list1,list2)] TypeError: unsupported operand type(s) for -: 'str' and 'str' – Giki Apr 22 '20 at 09:49
  • Thanks its working perfectly now :-)) .My apologies, I should have mentioned that the list contained strings earlier. – Giki Apr 22 '20 at 10:01
3

If your lists can be of different lengths, use zip_longest:

from itertools import zip_longest

list3 = [x-y for x,y in zip_longest(list1,list2, fillvalue=0)]

If the lists have the same length, it behaves like the usual zip, if not, it fills the shortest list with fillvalue (in this case zeros) to match the length of the other, instead of ignoring the remaining elements.

If your list contains strings, you're better off using string manipulation methods and changing the fillvalue.

from itertools import zip_longest

list3 = [str(x) + '-' + str(y) for x,y in zip_longest(list1,list2, fillvalue="")]
RMPR
  • 3,368
  • 4
  • 19
  • 31
  • Hi both the lists contain strings. I have tried what you mentioned but I am getting an error. TypeError Traceback (most recent call last) in ----> 1 list3 = [x-y for x,y in zip(list1,list2)] in (.0) ----> 1 list3 = [x-y for x,y in zip(list1,list2)] TypeError: unsupported operand type(s) for -: 'str' and 'str' – Giki Apr 22 '20 at 09:51