'Grab the pair of different items from two lists in Python
I am trying to create a file with only the pairs of items that differ in two lists. I would like it to be position limited: L1 [0] != L2[0] --True (I want it!). L1 1 != L21 --False (I don't want it). However, my code is comparing each item from L1 with each item from L2 and returning undesired pairs.
l1 = ["pear", "papaya", "guava"]
l2= ["grape", "pear", "guava"]
I just would like to have :
pear: grape
papaya: pear
Solution 1:[1]
If you can assume the length.. then you can simply take the index and compare equal indexes.
l1 = ["pear", "papaya", "guava"]
l2= ["grape", "pear", "guava"]
for index in range(len(l1)):
if (l1[index] != l2[index]):
print(f'{l1[index]}: {l2[index]}')
Solution 2:[2]
Assuming the you lists have same length you can use the build-in function zip which return a generator of pairs.
l1 = ["pear", "papaya", "guava"]
l2= ["grape", "pear", "guava"]
print([f'{i}: {j}' for i, j in zip(l1, l2) if i != j])
If the length are different a combinatorics approach is suggested.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ??? |
| Solution 2 | cards |

