ASANT
ASANT

Reputation: 421

Difference between two string list without using SET

I have two string lists:

list1 = ["python", "java", "perl", "sql"]
list2 = [ "scala", "python", "perl"]

I need a difference list like:

difference = ["java", "sql", "scala"]

I tried:

def stringDifference(list1, list2):
    difference = []
    for i in list1:
        if i not in list2:
            difference.append(i)
    for i in list2:
        if i not in list1:
            difference.append(i)
    print difference

But I just wanted to see if there is any efficient way than this solution in Python version less than 3.

Upvotes: 0

Views: 111

Answers (3)

martineau
martineau

Reputation: 123481

Although you can leave the lists as they are, it's likely faster to turn them both into dictionaries first which allow fast membership testing like sets do:

list1 = ["python", "java", "perl", "sql"]
list2 = [ "scala", "python", "perl"]

d1 = dict.fromkeys(list1)
d2 = dict.fromkeys(list2)
difference = [i for i in d1 if i not in d2] + [i for i in d2 if i not in d1]

print difference

Upvotes: 1

Hackaholic
Hackaholic

Reputation: 19743

using collections.Counter:

>>> from collections import Counter
>>> list1 = ["python", "java", "perl", "sql"] 
>>> list2 = [ "scala", "python", "perl"]
>>> [ x for x,y in Counter(list1+list2).items() if y==1 ]
['sql', 'java', 'scala']

using count:

>>> my_list = list1+list2
>>> [ x for x in my_list if my_list.count(x)==1 ]
['java', 'sql', 'scala']

set is better but you asked:

>>> [x for x in list1 if x not in list2 ]+ [ x for x in list2 if x not in list1]
['java', 'sql', 'scala']

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117946

You could add the result of two list comprehensions

>>> list1 = ["python", "java", "perl", "sql"]
>>> list2 = [ "scala", "python", "perl"]
>>> [i for i in list1 if i not in list2] + [i for i in list2 if i not in list1]
['java', 'sql', 'scala']

Upvotes: 2

Related Questions