Python | Add the occurrence of each number as sublists
Last Updated :
07 Jan, 2023
Given a list of numbers, the task is to count the occurrence of each element and add as sublists.
Examples:
Input: l1 = [3, 5, 7, 2, 3, 5, 9.1]
Output: [[3, 2], [5, 2], [7, 1], [2, 1], [9.1, 1]]
Input: l1 = [1, 1, 2, 2, 3, 1]
Output: [[1, 3], [2, 2], [3, 1]]
Note: Format output 2d list is [['item1', 'count1'], ['item2', 'count2'], ..., ['itemN', 'countN']].
Code #1: Using count() method
python
# Python program to add the occurrence
# of each number as sublists
def count_occur(list1, **kwargs):
# iterate over list item
for i in list1:
row =[]
ct = 0
# count function will count occurrence
ct = list1.count(i)
row.append(i)
row.append(ct)
# append 1d list items to 2d list
list2.append(row)
# below code is to eliminate
# repetitive list items
for j in list2:
if j not in unq_l2:
unq_l2.append(j)
return unq_l2
# Driver Code
l1 = [3, 5, 7, 2, 3, 5, 9.1]
list2 = []
unq_l2 = []
print(count_occur(l1))
Output:[[3, 2], [5, 2], [7, 1], [2, 1], [9.1, 1]]
Code #2: Using loop method
python
def count_occur(list1):
for i in range(0, len(l1)):
a = 0
row =[]
if i not in l:
for j in range(0, len(l1)):
# matching items from both lists
if l1[i]== l1[j]:
# on match counter increments by 1
a = a + 1
row.append(l1[i])
row.append(a)
# append function will append
# 1d list items to 2d list
l.append(row)
# below code is to eliminate
# repetitive list items
for j in l:
if j not in unq_l:
unq_l.append(j)
return unq_l
# Driver code
l1 =[3, 5, 7, 2, 3, 5, 9.1]
l =[]
unq_l =[]
print(count_occur(l1))
Output:[[3, 2], [5, 2], [7, 1], [2, 1], [9.1, 1]]
Code #3: Using counter() method
python
# Python program to add the occurrence
# of each number as sublists using counter() method
from collections import Counter
def count_occurence(l):
c = Counter(l)
l1 = []
for k,v in c.items():
l1.append([k,v])
return l1
# Driver code
l = [3, 5, 7, 2, 3, 5, 9.1]
print(count_occurence(l))
Output:[[2, 1], [3, 2], [9.1, 1], [5, 2], [7, 1]]
Code #4: Using set and list comprehension
You can use a set to eliminate duplicates in the input list and a list comprehension to count the occurrence of each element.
Python3
# Python program to add the occurrence
# of each number as sublists
def count_occur(l):
unique_elements = set(l)
return [[elem, l.count(elem)] for elem in unique_elements]
# Driver code
l1 = [3, 5, 7, 2, 3, 5, 9.1]
print(count_occur(l1))
Output[[2, 1], [3, 2], [5, 2], [7, 1], [9.1, 1]]
The time complexity of this approach is O(n^2) because it uses two nested loops. The outer loop iterates over the elements of the list, and the inner loop counts the number of occurrences of each element. The space complexity is O(n) because it creates a new list with the same number of elements as the input list.
Similar Reads
Python | Count occurrence of all elements of list in a tuple Given a tuple and a list as input, write a Python program to count the occurrences of all items of the list in the tuple. Examples: Input : tuple = ('a', 'a', 'c', 'b', 'd') list = ['a', 'b'] Output : 3 Input : tuple = (1, 2, 3, 1, 4, 6, 7, 1, 4) list = [1, 4, 7] Output : 6 Approach #1 : Naive Appro
5 min read
Python | Mean of consecutive Sublist Some of the classical problems in programming domain comes from different categories and one among them is finding the mean of subsets. This particular problem is also common when we need to compute the average and store consecutive group mean. Letâs try different approaches to this problem in pytho
3 min read
Python - Merge elements of sublists In Python, we often need to combine multiple sublists into a single list. This can be useful when dealing with data that is organized in smaller chunks, like rows in a table or pages in a document. Using itertools.chain()itertools.chain() function is one of the most efficient ways to merge sublists.
4 min read
Python - Sort list of numbers by sum of their digits Sorting a list of numbers by the sum of their digits involves ordering the numbers based on the sum of each individual digit within the number. This approach helps prioritize numbers with smaller or larger digit sums, depending on the use case.Using sorted() with a Lambda Functionsorted() function w
2 min read
Count the Sublists Containing given Element in a List - Python Given a list of lists our task is to count the number of sublists containing the given element x. For example: li = [[1, 3, 5], [1, 3, 5, 7], [1, 3, 5, 7, 9]] and x = 1 then output will be 3.Using List ComprehensionThis method uses list comprehension to check for the presence of the given element in
2 min read
Get the indices of all occurrences of an element in a list - Python We are given a list and our task is to find all the indices where a particular element occurs. For example, if we have a list like [1, 2, 3, 2, 4, 2] and the element is 2, then the output will be [1, 3, 5] because 2 appears at these positions.Using List ComprehensionList comprehension allows for a c
2 min read
Python - Occurrence counter in List of Records Sometimes, while dealing with records we can have a problem in which we need count the occurrence of incoming digits corresponding to different characters/players in a game and compile them in a dictionary. This can have application in gaming and web development. Lets discuss a way in which this can
2 min read
Python | Adding value to sublists Sometimes, we just have to manipulate a list of lists by appending a similar value to all the sublists. Using a loop for achieving this particular task can be an option but sometimes leads to sacrificing the readability of code. It is always wanted to have a oneliner to perform this particular task.
6 min read
Check for Sublist in List-Python The task of checking for a sublist in a list in Python involves determining whether a given sequence of elements (sublist) appears consecutively within a larger list. This is a common problem in programming, particularly in data processing and pattern matching. For example, if we have a list [5, 6,
4 min read
Python - Count frequency of Sublist in given list Given a List and a sublist, count occurrence of sublist in list. Input : test_list = [4, 5, 3, 5, 7, 8, 3, 5, 7, 2, 3, 5, 7], sublist = [3, 5, 7] Output : 3 Explanation : 3, 5, 7 occurs 3 times. Input : test_list = [4, 5, 3, 5, 8, 8, 3, 2, 7, 2, 3, 6, 7], sublist = [3, 5, 7] Output : 0 Explanation :
3 min read