w3resource

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


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

Sample Solution:

Python Code:

# Import the Counter class from the collections module
from collections import Counter

# Import the chain function from the itertools module
from itertools import chain

# Create a list of lists 'nums' with integer values
nums = [
    [1, 2, 3, 2],
    [4, 5, 6, 2],
    [7, 1, 9, 5],
]

# Print a message to indicate the display of the original list of lists
print("Original list of lists:")

# Print the content of 'nums'
print(nums)

# Print a message to indicate the display of the frequency of elements in the list of lists
print("\nFrequency of the elements in the said list of lists:")

# Count the frequency of elements in 'nums' by flattening it and using Counter
result = Counter(chain.from_iterable(nums))

# Print the result
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:

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

Python Code Editor:

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.



Follow us on Facebook and Twitter for latest update.