2

I'm trying to find the common elements of two lists using python 3, and have a new list with the common elements appearing only once. This is what I have so far:

lengtha = len(lista);
lengthb = len(listb);

identical = [];
checker = 0;

for i in range (0, lengtha-1):
    for j in range (0, lengthb-1):
        if lista[i] == listb[j]:
            length = len(identical);
            for h in range (0, length-1):
                if lista[i] == identical[h]:
                checker = 1;
            if checker == 0:
                identical.append(list[i]);
            checker = 0;

When I tried it with the lists

lista = ['hello', 'cat', 'dog', 'dog']
listb = ['hello', 'cat', 'cat', 'mouse', 'whale', 'whale', 'elephant', 'whale', 'elephant', 'dog', 'dog']

The result was ['hello','cat','cat','dog']. I can't figure out why 'cat' shows up twice and other duplicated animals didn't.

martineau
  • 119,623
  • 25
  • 170
  • 301
Maria
  • 35
  • 1
  • 6

1 Answers1

8

Use sets, its like a list, but can only hold unique items:

set(lista).intersection(listb)
Aule Mahal
  • 688
  • 5
  • 10