w3resource

Python: Sum of all counts in a collections

Python Basic: Exercise-125 with Solution

Write a Python program to sum of all counts in a collections.

Pictorial Presentation:

Sum of all counts in a collections

Sample Solution-1:

Python Code:

import collections
num = [2,2,4,6,6,8,6,10,4]
print(sum(collections.Counter(num).values()))
  

Sample Output:

9

Visualize Python code execution:

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


Sample Solution-2:

Python Code:

nums = [2,2,4,6,6,8,6,10,4]
print(len(nums))
  

Sample Output:

9

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 check if multiple variables have the same value.
Next: Write a Python program to get the actual module object for a given object.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Try-catch-else construct:

try:
  foo() 
except Exception: 
  print("Exception occured")
else:
  print("Exception didnt occur")
finally:
  print("Always gets here")