Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with lists in Python [duplicate]

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.

like image 280
Bernard Finucane Avatar asked Jul 02 '26 09:07

Bernard Finucane


2 Answers

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).
like image 124
Alex Hall Avatar answered Jul 03 '26 22:07

Alex Hall


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

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

like image 39
Rouzbeh Avatar answered Jul 03 '26 23:07

Rouzbeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!