Search code examples
pythonduplicatesnested-lists

Remove duplicate value on nested list python


I have a problem here when I want to remove duplicate in a list that has a nested list, how can I remove the duplicate value from list? What I got here from my script, it can remove a duplicate, but the nested list has a different result from what I expect.

This is my script:

# initializing list 
result = []
hasil = []
sam_list = [[11, 17, 11, 13, 13, 15, 16, 11], [4, 7, 11, 34, 4, 7, 11, 6], [1, 6, 11, 13, 13, 4, 1, 6]]

for item in sam_list:
    print("START")
    for x in item:
        print(x, result)
        if x not in result:
            print("NOT IN")
            result.append(x)
    hasil.append(result)

Result:

[[11, 17, 13, 15, 16, 4, 7, 34, 6, 1], [11, 17, 13, 15, 16, 4, 7, 34, 6, 1], [11, 17, 13, 15, 16, 4, 7, 34, 6, 1]]

Expected Result:

[[11, 17, 13, 15, 16], [4, 7, 11, 34, 6], [1, 6, 11, 13, 4]]

Solution

  • You need to initialize result = [] inside the loop:

    sam_list = [[11, 17, 11, 13, 13, 15, 16, 11], [4, 7, 11, 34, 4, 7, 11, 6], [1, 6, 11, 13, 13, 4, 1, 6]]
    hasil = []
    
    for item in sam_list:
        result = []
        print("START")
        for x in item:
            print(x, result)
            if x not in result:
                print("NOT IN")
                result.append(x)
        hasil.append(result)
    

    If you don't mind order:

    original = [[11, 17, 11, 13, 13, 15, 16, 11], [4, 7, 11, 34, 4, 7, 11, 6], [1, 6, 11, 13, 13, 4, 1, 6]]
    
    [list(set(each)) for each in original]