incrementing list values Python 3
Question: 
    infile = open('numbers.txt','r')
    
    c = 0
    for i in infile:
        if int(i) > c:
            c = int(i)
    hist = [0]*c
    
    for i in infile:   #checking
        ii = int (i)-1
        hist[ii] += 1  # problem area seemingly
    
    for i in range(c):
        print(str(i+1),':',end=' ')
        print(str(hist[i]))
    

The purpose of the code above is to open number.txt, which has a 100 numbers,
all within range(1,101), all with '\n' characters at their ends, and to count
the number of times each number has been encountered.

First the greatest number in the file is found, then a list with the number of
element equals the greatest number in the file, is made with all elements
initially set to zero. Then the numbers are checked. All numbers in file are
integers.

If the greatest number contained in the file is 100, then the hist[] list has
initially 100 elements which are all 0.

During checking, say if a number 78 is encountered, the element with index
[77] ie hist[77] is updated from value 0 to 1. If 78 is encountered again,
hist[77] is changed from 1 to 2.

This way whatever number occurs in the file, each occurring number has a
counter (also numbers that don't appear but are less that the greatest
occurring no. have counters but thats not a problem).

Having checked that the correct file is being opened, the hist list is
initially being set up properly, the problem is that the values of the hist[]
list are not getting increment when the corresponding number is being
encountered. When i print the list at the end, all values are still zero.

I am using Python 3.4.3. Both the script and 'numbers.txt' are on my desktop.
Any help appreciated.


Answer: You are looping over the file twice, but did not rewind the file reading
pointer to the start. Add a `file.seek()` call before the second loop:

    
    
    infile.seek(0)
    for i in infile:   #checking
    

Without the `seek` iteration over `infile` will not yield any further lines;
you reached the end of the file _already_.

You'd be better off using a [`collections.Counter()`
object](https://docs.python.org/2/library/collections.html#collections.Counter)
here though:

    
    
    from collections import Counter
    
    with open('numbers.txt','r') as infile:
        hist = Counter(int(line) for line in infile)
    

You can then either get the highest counted number using `max(hist)` or
instead retrieve the numbers in most common to least order with the
`Counter.most_common()` method:

    
    
    # In numerical order, setting missing numbers to 0
    for i in range(1, max(hist) + 1):
        print('{}: {}'.format(i, hist.get(i, 0)))
    
    # In most common to least order
    # In numerical order
    for number, count in hist.most_common():
        print('{}: {}'.format(number, count))
    

