3

Possible Duplicate:
Python: removing duplicates from a list of lists

What is the best way to remove duplicates from a list of lists?

I was trying to use set like this:

L1 = [['fox', 'dog'],['bat', 'rat'],['fox', 'dog']]  
L1 = list(set(L1))

Unfortunately, I get a TypeError: unhashable type: 'list'.

In my list there are two occurrences of ['fox', 'dog']. I want L1 to remove the duplicate and look like this:

L1 = [['fox', 'dog'],['bat', 'rat']]

Community
  • 1
  • 1
drbunsen
  • 10,139
  • 21
  • 66
  • 94

1 Answers1

9

If you convert the inner lists to tuples you will be able to add them to a set successfully, for example:

>>> set(map(tuple, L1))
set([('fox', 'dog'), ('bat', 'rat')])

If necessary, you can get back to lists of lists like this:

>>> map(list, set(map(tuple, L1)))
[['fox', 'dog'], ['bat', 'rat']]
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306