How to delete those 1D lists within a 2D list which contains with duplicate 1st element?

Viewed 62

Say I have a 2D list(of floats only)-

a=[[1,2],[1,3],[2,5],[4,3],[3,4],[4,9]] and I want to remove those 1D lists which have the common 1st element and occur later. For example- the first list [1,2] contains 1 as the first element, so delete the next list with 1st element 1, which in this case is the 2nd list [1,3], then we take [2,5],[4,3],[3,4] as usual but since we took [4,3] already we won't take the [4,9] which has the common first element 4.

So the final output should be-

[[1,2],[2,5],[4,3],[3,4]]

How can this be done in Python? I can think of some nested for loops and a bunch of if else statements which would be clearly inefficient and I hope there is a trick with set/map/zip functions which is a bit more Pythonic.

2 Answers

Use set() to filter out the duplicates:

a = [[1, 2], [1, 3], [2, 5], [4, 3], [3, 4], [4, 9]]

out, seen = [], set()
for item in a:
    if not item[0] in seen:
        seen.add(item[0])
        out.append(item)

print(out)

Prints:

[[1, 2], [2, 5], [4, 3], [3, 4]]
a=[[1,2],[1,3],[2,5],[4,3],[3,4],[4,9]]
k=[]
[a.remove(i) if i[0] in k else k.append(i[0]) for i in a]
print(a)
Related