0

for example,

a = [[1, 2], [2, 3], [1, 2]]

I need it to be

a = [[1, 2], [2, 3]]

since [1, 2] is duplicated.

set cannot be used because it did not accept a mutable object. and I know changing list to a tuple works. But is there a clean way if I want to keep them as lists? (not using numpy array)

qiuweikang
  • 47
  • 4
  • What is unclean about converting to tuple then using a set? Seems pretty clean to me. – juanpa.arrivillaga Mar 09 '21 at 02:28
  • https://www.geeksforgeeks.org/python-get-unique-values-list/amp/ – Niloct Mar 09 '21 at 02:29
  • 2
    Someone already had this problem! Is [this answer](https://stackoverflow.com/questions/3724551/python-uniqueness-for-list-of-lists) helpful to you? c: – spagh-eddie Mar 09 '21 at 02:29
  • If you want to maintain order, `list(map(list, dict.fromkeys(map(tuple, a))))` – juanpa.arrivillaga Mar 09 '21 at 02:30
  • 1
    @spaghEddie Yes. I searched but I did not find that. thanks. – qiuweikang Mar 09 '21 at 02:37
  • This is not the most efficient, but you can do `b = [x for i,x in enumerate(a) if x not in a[:i]]` – Joe Ferndz Mar 09 '21 at 02:37
  • 3
    Is there any _reason_ why you want to keep them as lists? If not, it reads more like a useless puzzle that most people will not want to spend time trying to answer. Any time a restriction is introduced in the question that clearly prevents the optimal and natural solution, I wonder why anyone would ask "how to eat soup without spoons (or drinking it)" — just use the dang spoon. :) "I have a metal and plastic allergy so I can't use spoons" makes the question so much better. – Amadan Mar 09 '21 at 02:37

2 Answers2

1

You could try something like this

a = [a[i] for i in range(len(a)) if a.index(a[i]) == i]

Which includes an item in a only if it's the first occurence

0

First, you can transform your list of lists into a list of tuples:

a = [tuple(l) for l in a]

Then, you can transform a into a set:

>>> set(a)
set([(1, 2), (2, 3)])
Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82