Python Practice › List Programs › Program 72

Keep sublists that are not repeated

EasyList Programs · 72 of 100

Write a Python program to keep only the sublists that appear once.

Advertisement
Input
[[1, 2], [3, 5], [1, 2], [6, 7]]
Output
[[3, 5], [6, 7]]

Approach

  1. Count tuples (lists are unhashable), keep those with count 1.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment