Numbers that appear exactly once
Write a Python program to get the numbers that appear exactly once in a list.
[1, 2, 2, 3, 4, 4, 5]
[1, 3, 5] [1, 2, 3, 4, 5]
Approach
- Count with
Counterand keep counts of 1.
Solution
from collections import Counter numbers = [1, 2, 2, 3, 4, 4, 5]counts = Counter(numbers)print([n for n in numbers if counts[n] == 1])print(list(dict.fromkeys(numbers)))[1, 3, 5] [1, 2, 3, 4, 5]
Line by line
Values that occur only once.
Every distinct value (duplicates removed), for comparison.
Learn the concept
New to this topic? Read the lesson, then come back.