Search code examples
pythonlistindexinghistogramtraceback

Printing a histogram


I have a list of integer percentages which I need to print using the following pattern:

The index of a value, a tab (8 spaces), a '*' printed for each percentage point

also if the value for an index is 0, print 'less than 1 percent'

I have tried this code:

for b in new_tally:
    if b > 0:
        print new_tally[b], \t, '*' * b
    else:
        print 'Less than 1% of words had this length'

However I keep getting the error code: list index out of range.

I do not understand this at all, can someone point out what I have done wrong?


Solution

  • I think the code you wanted was:

    >>> new_tally = [5, 7, 8, 6, 4, 2]
    >>> for i, b in enumerate(new_tally, 1):
            print i, ':', b, '*' * b
    
    1 : 5 *****
    2 : 7 *******
    3 : 8 ********
    4 : 6 ******
    5 : 4 ****
    6 : 2 **
    

    The cause of the original traceback is that list members are looked up using square brackets instead of parentheses. new_tally(i) is a function call. new_tally[i] is an indexed lookup.