w3resource

Python: Iterate over elements repeating each as many times as its count

Python Collections: Exercise-1 with Solution

Write a Python program that iterates over elements as many times as its count.

Note: Elements are returned in arbitrary order.

Sample Solution:

Python Code:

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

# Create a Counter object 'c' with specified initial counts for keys 'p', 'q', 'r', and 's'
c = Counter(p=4, q=2, r=0, s=-2)

# Print the elements in the Counter 'c' as a list
print(list(c.elements())) 

Sample Output:

['p', 'p', 'p', 'p', 'q', 'q']  

Flowchart:

Flowchart - Python Collections: Iterate over elements repeating each as many times as its count.

Python Code Editor:

Previous: Python Tuple Exercise Home.
Next: Write a Python program to find the most common elements and their counts of a specified text.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://198.211.115.131/python-exercises/collections/python-collections-exercise-1.php