Add the occurrence of each number as sublists in Python

When working with lists containing duplicate elements, you may need to create sublists that show each unique element paired with its frequency count. Python provides several approaches to accomplish this task effectively.

Using For Loop and Append

This approach compares each element with every other element in the list to count occurrences. We track processed elements to avoid duplicates in the result ?

Example

def count_occurrences_manual(numbers):
    result = []
    processed = []
    
    for i in range(len(numbers)):
        if numbers[i] not in processed:
            count = 0
            for j in range(len(numbers)):
                if numbers[i] == numbers[j]:
                    count += 1
            result.append([numbers[i], count])
            processed.append(numbers[i])
    
    return result

# Test the function
numbers = [13, 65, 78, 13, 12, 13, 65]
print("Number of occurrences of each element:")
print(count_occurrences_manual(numbers))

The output of the above code is ?

Number of occurrences of each element:
[[13, 3], [65, 2], [78, 1], [12, 1]]

Using Counter from Collections

The Counter class from the collections module provides a more efficient way to count occurrences. It automatically handles the counting logic ?

Example

from collections import Counter

def count_occurrences_counter(numbers):
    counter = Counter(numbers)
    result = []
    for element, count in counter.items():
        result.append([element, count])
    return result

# Test the function
numbers = [13, 65, 78, 13, 12, 13, 65]
print("Number of occurrences of each element:")
print(count_occurrences_counter(numbers))

The output of the above code is ?

Number of occurrences of each element:
[[13, 3], [65, 2], [78, 1], [12, 1]]

Using List Comprehension with Counter

You can make the Counter approach even more concise using list comprehension ?

Example

from collections import Counter

def count_occurrences_compact(numbers):
    return [[element, count] for element, count in Counter(numbers).items()]

# Test the function
numbers = [13, 65, 78, 13, 12, 13, 65]
print("Number of occurrences of each element:")
print(count_occurrences_compact(numbers))

The output of the above code is ?

Number of occurrences of each element:
[[13, 3], [65, 2], [78, 1], [12, 1]]

Comparison

Method Time Complexity Readability Best For
Manual For Loop O(n²) Medium Educational purposes
Counter O(n) High Production code
List Comprehension O(n) High Compact solutions

Conclusion

Use Counter from collections for efficient counting of element occurrences. The manual approach helps understand the logic, while list comprehension provides the most concise solution.

Updated on: 2026-03-15T18:08:27+05:30

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements