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,641
  • 9
  • 36
  • 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
  • 8,406
  • 5
  • 28
  • 34
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,472
  • 18
  • 22
0
return [el for el in b if el not in a]
6160
  • 1,002
  • 6
  • 15