3

I have two non-unique lists of values, such as

["a", "b", "a", "c"] 

and

 ["a", "b", "b", "f"]

I want to find which elements of the second list do not appear in the first.

I could code this by hand, but would prefer to use built-in functions. I can't figure out how because I keep bumping into the hashable / unhashable barrier.

Jared Goguen
  • 8,772
  • 2
  • 18
  • 36

2 Answers2

8

In this case it would be

set(second_list) - set(first_list)

because strings are hashable and you can put them in sets. If you have non-hashable values then tell us what they are and we can probably come up with a workaround. For example:

  • You can convert a list to a tuple using tuple(the_list), can back using list(the_tuple).
  • You can convert a set to a tuple using tuple(the_set), can back using set(the_tuple).
  • You can convert a nested list to a nested tuple using tuple(map(tuple, the_list)) and back using list(map(list, the_tuple)).
  • You can convert a dictionary to a nested tuple using tuple(the_dict.items()) and back using dict(the_tuple).
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
1

[x for x in ListB if x not in ListB]

I think this is a pretty fast way you can use.

Rouzbeh
  • 2,141
  • 1
  • 11
  • 19