0

I have two lists. How can I define a function "remove_repeat_element" to remove repeat elements from them ? ?

def remove_repeat_element(a, b):
    ... ...

a = ['bd09fdf7-918e-4a5e-8338-0f6fe78fd238']
b = ['bd09fdf7-918e-4a5e-8338-0f6fe78fd238', '3c26f383-da50-446c-8613-64e1068bd57e']

result = remove_repeat_element(a, b)
print result
>>> ['3c26f383-da50-446c-8613-64e1068bd57e']

Could someone give me some advice ?? Thanks a lot!

changzhi
  • 2,461
  • 9
  • 33
  • 46

3 Answers3

10

You can use sets :

>>> a = ['bd09fdf7-918e-4a5e-8338-0f6fe78fd238']
>>> b = ['bd09fdf7-918e-4a5e-8338-0f6fe78fd238', '3c26f383-da50-446c-8613-64e1068bd57e']
>>> list(set(b) - set(a))
['3c26f383-da50-446c-8613-64e1068bd57e']
Faruk Sahin
  • 7,916
  • 5
  • 26
  • 32
2

My suggestion:

c = [x for x in b if x not in a]

It is pretty straight forward to write and efficient enough as a list comprehension.

Hope this helps!

Update:

For more efficient membership checking, use set instead of list.

a = set(a)
c = [x for x in b if x not in a]

This would be even faster and not to mention the improvement when the list is large.

Ray
  • 2,452
  • 17
  • 21
0
return [el for el in b if el not in a]
6160
  • 990
  • 5
  • 15