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 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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/collections/python-collections-exercise-29.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics