Loops and totals in Python
Question: I am trying to write a program to draw a histogram of the lengths of words
present in a list, so far I am up the stage of increasing the number of words
present of a certain length by one every time the loop finds a word with that
certain length, at the moment I have:

    
    
    L = []
    for i in range(L):
    length = len(i)
    for len(i) = 1:
        total1 = total1 + 1
    for len(i) = 2:
        total2= total2 + 1
    for len(i) = 3:
        total3 = total3 + 1
    for len(i) = 4:
        total4 = total4 + 1
    for len(i) = 5:
        total5 = total5 + 1
    

However clearly this is a stupid method as it involved naming each version of
totaln, where in this case n would be up to 11, so my question is can I simply
put

    
    
    L = []
    for i in range(L):
    length = len(i)
    for len(i) = n:
        totaln = totaln + 1
    

to cover all values of n, and then refer to for example total4 later? Or will
the interpreter return an error as total4 isn't explicitly defined?

As for the rest of the code I think I can work that bit out, it's just this
issue I am having trouble with, being very new to programming.


Answer: In Python 2.7 or above, you could use a
[`Counter`](http://docs.python.org/library/collections.html#collections.Counter):

    
    
    from collections import Counter
    a = ["basically", "in", "Python", "I", "am", "trying", "to", "write",
         "a", "program", "to", "draw", "a", "histogram", "of", "the",
         "lengths", "of", "words", "present", "in", "a", "list"]
    print Counter(map(len, a))
    

prints

    
    
    Counter({2: 7, 1: 4, 7: 3, 4: 2, 5: 2, 6: 2, 9: 2, 3: 1})
    

which is a dictionary mapping word lengths to frequencies.

