Giki
Giki

Reputation: 27

How to merge two lists simultaneously?

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']

Upvotes: 0

Views: 145

Answers (2)

RMPR
RMPR

Reputation: 3511

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="")]

Upvotes: 3

Farhood ET
Farhood ET

Reputation: 1541

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)]

Upvotes: 4

Related Questions