Python Practice › List Programs › Program 72
Keep sublists that are not repeated
Write a Python program to keep only the sublists that appear once.
Input
[[1, 2], [3, 5], [1, 2], [6, 7]]
Output
[[3, 5], [6, 7]]
Approach
- Count tuples (lists are unhashable), keep those with count 1.
Solution
from collections import Counter data = [[1, 2], [3, 5], [1, 2], [6, 7]]counts = Counter(tuple(x) for x in data)print([x for x in data if counts[tuple(x)] == 1])Output
[[3, 5], [6, 7]]
Line by line
Line 4
Converting each sublist to a tuple makes it countable.
Learn the concept
New to this topic? Read the lesson, then come back.