Get unique items from a list of lists?

I have a list of lists that looks like this:

animal_groups = [['fox','monkey', 'zebra'], ['snake','elephant', 'donkey'],['beetle', 'mole', 'mouse'],['fox','monkey', 'zebra']] 

What is the best way to remove duplicate lists? Using the above example, I am looking for code that would do this:

 uniq_animal_groups = [['fox','monkey', 'zebra'], ['snake','elephant', 'donkey'],['beetle', 'mole', 'mouse']] 

At first I thought I could use set() , but this does not seem to work in a list of lists. I also saw an example using itertools , but the code is not entirely clear to me. Thanks for the help!

+7
source share
3 answers
 uniq_animal_groups = set(map(tuple, animal_groups)) 

will do the trick, although in the end you will get a set of tuples instead of a set of lists. (Of course, you can convert this back to a list of lists, but if there is no specific reason for this, why bother?)

+15
source

Convert lists to tuples, and then you can put them into a set.

Essentially:

 uniq_animal_groups = set(map(tuple, animal_groups)) 

If you prefer the result to be a list of lists, try:

 uniq_animal_groups = [list(t) for t in set(map(tuple, animal_groups))] 

or

 uniq_animal_groups = map(list, set(map(tuple, animal_groups))) 
+5
source

When you don't care about sorting internal lists, first convert everything to settings:

 uniq_animal_groups = map(list, set(map(tuple, map(set, animal_groups)))) 
0
source

All Articles