12

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 to remove duplicate lists? Using the above example, I am looking for code that would produce this:

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

I first thought I could use set(), but this doesn't appear to work on a list of lists. I also saw an example using itertools, but the code was not entirely clear to me. Thanks for the help!

drbunsen
  • 10,139
  • 21
  • 66
  • 94

3 Answers3

21
uniq_animal_groups = set(map(tuple, animal_groups))

will do the trick, though you will end up with a set of tuples instead of a set of lists. (Of course you could convert this back to a list of lists, but unless there is a specific reason to do so, why bother?)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • incase you want to access the list of lists (eg. inspect `uniq_animal_groups[0]`, do `uniq_animal_groups = list(set(map(tuple, animal_groups)))` instead. – sachinruk Dec 22 '16 at 05:36
5

Convert the 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)))
Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88
0

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

uniq_animal_groups  = map(list, set(map(tuple, map(set, animal_groups))))
Greg Funtusov
  • 1,377
  • 15
  • 18