﻿ Python: Sum of all counts in a collections - w3resource

# Python: Sum of all counts in a collections

## Python Basic: Exercise-125 with Solution

Write a Python program to sum all counts in a collection.

Pictorial Presentation:

Sample Solution-1:

Python Code:

``````# Import the 'collections' module, which provides the 'Counter' class.
import collections

# Define a list of numbers.
num = [2, 2, 4, 6, 6, 8, 6, 10, 4]

# Use 'collections.Counter' to count the occurrences of each number and sum the values.
# 'collections.Counter' returns a dictionary-like object with elements as keys and their counts as values.
# 'sum(collections.Counter(num).values())' calculates the sum of these counts.
result = sum(collections.Counter(num).values())

# Print the result, which is the sum of the counts.
print(result)
```
```

Sample Output:

```9
```

Sample Solution-2:

Python Code:

``````# Create a list 'nums' containing various integer values.
nums = [2, 2, 4, 6, 6, 8, 6, 10, 4]

# Calculate and print the length (number of elements) of the 'nums' list.
print(len(nums))
```
```

Sample Output:

```9
```

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿