0

I have a list containing ~300 lists, however some of them are duplicates and I would like to remove them. I've tried:

cleanlist = [cleanlist.append(x) for x in oldlist if x not in cleanlist]

but it keeps throwing RuntimeError: maximum recursion depth exceeded in comparison at me. I tried sys.setrecursionlimit(1500) but that didn't help.

What's a better way to do this?

jscs
  • 63,694
  • 13
  • 151
  • 195
Raspel
  • 283
  • 4
  • 16
  • 1
    How big are your lists? Are tuples maybe more appropriate? (They’re hashable, which makes getting a unique list – not in the right order, though – as easy as `list(set(oldlist))`.) – Ry- Jun 04 '15 at 00:53
  • 1
    You're adding a bunch of stuff to `cleanlist` based on whether it's in `cleanlist` (which doesn't exist yet), and then saving the value returned from the `append` operation (which is `None`) to `cleanlist`. It will not end well. – TigerhawkT3 Jun 04 '15 at 00:53
  • 1
    Have a look at [How do you remove duplicates from a list in Python whilst preserving order?](http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order) – Bhargav Rao Jun 04 '15 at 00:56
  • @BhargavRao: Many of the answers there won’t work on a list of lists. – Ry- Jun 04 '15 at 00:57

2 Answers2

6

You're adding a bunch of stuff to cleanlist based on whether it's in cleanlist (which doesn't exist yet), and then saving the value returned from the append() operation (which is None) to cleanlist. It will not end well.

A better way to do this is probably with an old-fashioned loop construct:

cleanlist = []
for x in oldlist:
    if x not in cleanlist:
        cleanlist.append(x)
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

A crazy solution. Maybe It helps:

oldlist = [[1,2,3], [1,2,3], [4,5,6], [7,8], [7,8]]
cleanlist = set(tuple(x) for x in oldlist)
print(list(cleanlist))

>>> [(7, 8), (4, 5, 6), (1, 2, 3)]

For a list of lists, use this:

cleanlist = [list(item) for item in set(tuple(x) for x in oldlist)]
>>> [[7, 8], [4, 5, 6], [1, 2, 3]]
João Paulo
  • 6,300
  • 4
  • 51
  • 80