w3resource

Python: Frequency of the elements in a given list of lists using collections module

Python Collections: Exercise-29 with Solution

Write a Python program to get the frequency of the elements in a given list of lists. Use collections module.

Sample Solution:

Python Code:

from collections import Counter
from itertools import chain
nums = [
        [1,2,3,2],
        [4,5,6,2],
        [7,1,9,5],
       ]
    
print("Original list of lists:")
print(nums)
print("\nFrequency of the elements in the said list of lists:")
result = Counter(chain.from_iterable(nums))
print(result)

Sample Output:

Original list of lists:
[[1, 2, 3, 2], [4, 5, 6, 2], [7, 1, 9, 5]]

Frequency of the elements in the said list of lists:
Counter({2: 3, 1: 2, 5: 2, 3: 1, 4: 1, 6: 1, 7: 1, 9: 1})

Flowchart:

Python Collections: Frequency of the elements in a given list of lists using collections module.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists. Use collections module.
Next: Write a Python program to count the occurrence of each element of a given list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Python: Tips of the Day

Use Reversed() In for Loops:

>>> tasks = ['laundry', 'picking up kids', 'gardening', 'cooking']
>>> for task in reversed(tasks):
...     print(task)
... 
cooking
gardening
picking up kids
laundry