Search code examples
pythonlistpython-3.xunique

I want to check for a specific element in a sublist and remove repeated sublists with the same element in python


i have this

lst = [['100','LA'],['101','NY'],['100','NC']]
lst2 = []

i need to check if there's any 100,101,etc repeated and remove the repeated numbers. So the second list would look like this

lst2=[['100','LA'],['101','NY']]

because the 100 was already added once in that second list


Solution

  • A quick and dirty way to do this is using a generic uniqueness filter:

    def uniqueness(iterable,key=lambda x:x):
        seen = set()
        for item in iterable:
            fitem = key(item)
            if fitem not in seen:
                yield item
                seen.add(fitem)
    

    You can then use it like:

    list2 = list(uniqueness(lst,key=lambda x:x[0]))
    

    If you do not specify, the filter will assume the entire element (but this will fail here, because list is not hashable).