w3resource

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


1. Iterate Over Elements as Many Times as Its Count

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.

For more Practice: Solve these Related Problems:

  • Write a Python program that uses a dictionary to count character frequencies in a string and then reconstruct a list where each character appears as many times as its count.
  • Write a Python program to take a list of tuples (element, count) and generate a new list by repeating each element by its count.
  • Write a Python program to implement a function that, given a string, returns a list with each letter repeated according to its frequency in the string.
  • Write a Python program to use collections.Counter on a string and then expand it back to a list where each character appears its count number of times.

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.



Follow us on Facebook and Twitter for latest update.