-1

I have two lists, heatmapNames and taxLabels.

heatmapNames = ['dog', 'walrus', 'cat', 'pig', 'orca', 'moose', 'bear', 'fox', 'salamander']

taxLabels = ['cat', 'deer', 'mouse', 'rat', 'walrus', 'orca', 'fox']

I am trying to produce two new lists. One containing the elements in both lists called sharedNames and one containing elements found only in heatmapNames called onlyHeatmapNames.

Here is the code I have to do this:

sharedNames = []
onlyHeatmapNames =[]
onlyTaxLabels = []
for heatmapName in heatmapNames:
    for taxLabel in taxLabels:
        if heatmapName in taxLabel:
            sharedNames.append(heatmapName)
    if heatmapName not in onlyHeatmapNames:  
        onlyHeatmapNames.append(heatmapName)

While the sharedNames list is correct, some of the elements in onlyHeatmapNames are also found in sharedNames. How can I solve this?

wilberox
  • 193
  • 10

1 Answers1

1

You would better do this:

sharedNames=[i for i in heatmapNames if i in taxLabels]
onlyHeatmapNames=[i for i in heatmapNames if i not in taxLabels]
onlyTaxLabels=[i for i in taxLabels if i not in heatmapNames]
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30