Search code examples
pythonlistunique

How to remove elements from a list of lists where an element is repeated?


I have a list of lists

my_list = [["a", "b", "c"],
           ["d", "f", "g"],
           ["h", "b", "i"]]

I want to remove all elements in my_list where element[1] is not unique. So the result after performing this operation is either

my_list = [["d", "f", "g"]] 

or a new list also works

new_list = [["d", "f", "g"]]

My current method is:

from collections import Counter

y_list = []

for element in my_list:
    x, y, z = element
    y_list.append(y)

count_dict = dict(Counter(y_list))

unique_y_list = []

for y, count in count_dict.items():
    if count == 1:
        unique_y_list.append(y)
 

valid_elements = []

for element in my_list:
    x, y, z = element
    if y in unique_y_list:
        valid_elements.append(element)

This works but doesn't seem efficient. Help with a more pythonic way to achieve my desired result? Preserving order is not important.


Solution

  • I'd create a Counter of elements in the index 1, and then use it to check if each list's element at index 1 is unique:

    from collections import Counter
    c = Counter(x[1] for x in my_list)
    result = [l for l in my_list if c[l[1]] == 1]