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:
JavaScript
x
14
14
1
# initializing list
2
result = []
3
hasil = []
4
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]]
5
6
for item in sam_list:
7
print("START")
8
for x in item:
9
print(x, result)
10
if x not in result:
11
print("NOT IN")
12
result.append(x)
13
hasil.append(result)
14
Result:
JavaScript
1
2
1
[[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]]
2
Expected Result:
JavaScript
1
2
1
[[11, 17, 13, 15, 16], [4, 7, 11, 34, 6], [1, 6, 11, 13, 4]]
2
Advertisement
Answer
You need to initialize result = []
inside the loop:
JavaScript
1
13
13
1
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]]
2
hasil = []
3
4
for item in sam_list:
5
result = []
6
print("START")
7
for x in item:
8
print(x, result)
9
if x not in result:
10
print("NOT IN")
11
result.append(x)
12
hasil.append(result)
13
If you don’t mind order:
JavaScript
1
4
1
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]]
2
3
[list(set(each)) for each in original]
4