Skip to content Skip to sidebar Skip to footer

Returning Only Unique Occurrences From A List Of Lists Based On The First Element

Apologies, I believe this is a common question, but cannot seem to find an exact answer for the desired outcome. I would like to return ONLY the unique items in a list of lists bas

Solution 1:

It may be tempting to use list.count but it will make the solution using it O(n^2) if used naively.

An O(n) solution would be using collections.Counter:

from collections import Counter

nested_list = [[1,2],[2,3],[1,4],[1,5],[6,3]]

counter_map = Counter(sublist[0] for sublist  in nested_list)
print(counter_map)
output = [sublist for sublist in nested_list if counter_map[sublist[0]] == 1]
print(output)

outputs

Counter({1: 3, 2: 1, 6: 1})
[[2, 3], [6, 3]]

Post a Comment for "Returning Only Unique Occurrences From A List Of Lists Based On The First Element"