Combine two lists without duplicate values

Viewed 9206
list1 = ["palani", "samy","be"]
list2 = ["palani", "samys","be"]

def find_common(list1,list2):
    for x in list1:
      for y in list2:
        if x == y :
          list2.remove(x) 


    print" unique string 1:",list1
    print" unique string 2:",list2
    print" combained string 2:",list1.append(list2)


find_common(list1,list2)

enter image description here

Why am I getting None?

6 Answers

This could be accomplished by using set:

a = ['hello', 'world']
b = ['hello', 'universe']

unique = list(set(a + b))

print(unique)

# ['universe', 'hello', 'world']

Note: this won't work for a list of dictionaries!

import numpy as np

np.unique(list1+list2) # keeps only non dublicates

this is also keeps the order incase that was a priority

The list.append method modifies the list in-place and returns None. You should use the + operator to merge the two lists instead.

Change:

print" combained string 2:",list1.append(list2)

to:

print" combained string 2:",list1+list2
list3 = list1[:]
[list3.append(i) for i in list2 if i not in list1] 

print(l3)
['palani', 'samy', 'be', 'samys']

you may try:

def find_common(list1,list2):
    return list(set(list1+list2))

You can use set operations to achieve this.

unique = list(set(list1).symmetric_difference(set(list2)))
Related