Python: Histogram

Python Basic: Exercise-26 with Solution

Write a Python program to create a histogram from a given list of integers.

Pictorial Presentation:

Create a histogram from a given list of integers

Sample Solution:

Python Code:

# Define a function called histogram that takes a list of items as a parameter.
def histogram(items):
    # Iterate through the items in the list.
    for n in items:
        output = ''  # Initialize an empty string called output.
        times = n     # Set the times variable to the value of n.
        # Use a while loop to append '*' to the output string 'times' number of times.
        while times > 0:
            output += '*'
            times = times - 1  # Decrement the times variable.
        # Print the resulting output string.

# Call the histogram function with a list of numbers and print the histogram.
histogram([2, 3, 6, 5])

Sample Output:



The function "histogram" takes a parameter "items ", a list of integers. To iterate through each item in the "items" list, the function uses a for loop. For each iteration, it creates a varaible "output", and assigns the current element (n) of the loop to the variable "times".

Then it uses a while loop which will run as long as the value of "times" is greater than 0. Inside the while loop, it concatenates an asterisk (*) character to the "output" variable and decrements the value of "times" by 1 at each iteration. After the while loop completes, it prints the final value of "output" variable.

The last line of code calls the "histogram" function with a list of integers ([2, 3, 6, 5]) as an argument, it will print a histogram of asterisks, where the number of asterisks corresponds to the value of the integers in the list.


Flowchart: Create a histogram from a given list of integers.

Python Code Editor:


Previous: Write a Python program to check whether a specified value is contained in a group of values.
Next: Write a Python program to concatenate all elements in a list into a string and return it.

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.