0

I'm trying to do something similar to this link, but using lists of lists. Doing the following, however, gives me a TypeError.

list1 = [[a,a], [b,b], [c,c]]
list2 = [[c,c], [d,d], [e,e]]

same = set(list1) & set(list2)

I'm also trying to find:

different = not set(list1) & set(list2)
Community
  • 1
  • 1
user25976
  • 1,005
  • 4
  • 18
  • 39
  • 1
    use tuples for the pairs instead of lists. The elements of a set have to be hashable – President James K. Polk Jul 25 '14 at 02:18
  • 2
    As a general rule, when you get a ``TypeError`` (or any error) it is helpful to post the error text along with your question. In this case the problem was easy to deduce, but it really is quite helpful to answerers on more complex problems. The errors generally tell you exactly what went wrong, once you know how to read them. – aruisdante Jul 25 '14 at 02:20
  • 1
    for `different` use `set(list1 + list2) - same` when `list1` and `list2` are a list of tuples. – ssm Jul 25 '14 at 02:26

2 Answers2

0

Lists are not hashable types, so they can't be put into sets, but tuples can. You can convert a list to a tuple with tuple(mylist). The following code assumes that a,b,c,d and e are hashable types.

list1 = [(a,a), (b,b), (c,c)]
list2 = [(c,c), (d,d), (e,e)]

same = set(list1) & set(list2)
Andrew Johnson
  • 3,078
  • 1
  • 18
  • 24
  • i ended up converting my list of lists to list of tuples using the map function. same = set(map(tuple, list1)) & set(map(tuple, list2)) – user25976 Jul 29 '14 at 21:06
0

It would be more readable and more understandable if you just used list comprehension like so ..

def seperate(*ls):
   sim, diff = []
   for l in ls:
       sim.extend([ x for x in l if x not in sim ])
       diff.extend([ x for x in l if x not in sim ])
   return sim, diff
Amr Ayman
  • 1,129
  • 1
  • 8
  • 24