incrementing values of a list at specific indexes python
Question: I am attempting to create a list for each nucleotide (A, G, C, T) in a
sequence where the index of the list corresponds to the position in the
sequence and the value is the frequency of that nucleotide across all
sequences, here are 4 sequences as an example:

    
    
    >ignore this
    GTAGGGCGA
    >ignore this
    GTATACAGC
    >ignore this
    GTTTCTCTT
    >ignore this
    GTAATCAAA
    

The code I've written:

    
    
    def function(filename, length):
        g,t,c,a = [],[],[],[]
        with open(filename, "r") as f:
            for line in f:
                if line.startswith('GT'):
                     gcount, acount, tcount, ccount = 0, 0, 0, 0
                     g = [gcount + 1 if nuc == 'G' else gcount for nuc in line[:length]]
                     return g
    

Right now, this code just looks at the G nucleotides and I get a list for
every sequence instead of 1 list that sums the values at each index of the
list.

    
    
    [1, 0, 0, 1, 1, 1, 0, 1, 0]
    [1, 0, 0, 0, 0, 0, 0, 1, 0]
    [1, 0, 0, 0, 0, 0, 0, 0, 0]
    [1, 0, 0, 0, 0, 0, 0, 0, 0]
    

What I would like as my output for g alone:

    
    
    [4, 0, 0, 1, 1, 1, 0, 2, 0]
    


Answer: You can use `numpy` for this. Just convert your lists to `numpy` arrays and
add.

    
    
    import numpy as np
    
    list1 = np.array([1, 0, 0, 1, 1, 1, 0, 1, 0])
    list2 = np.array([1, 0, 0, 0, 0, 0, 0, 1, 0])
    list3 = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0])
    list4 = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0])
    
    list1 + list2 + list3 +list4 # desired result!
    >>> array([4, 0, 0, 1, 1, 1, 0, 2, 0])
    

Here's how you can modify your current function to support this:

    
    
    def function(filename, length)
        g,t,c,a = [],[],[],[]
        # create an array of expected length of g filled with 0s
        base = np.zeros((1,length)) # 1 row, `length` number of columns
        with open(filename, "r") as f:
            for line in f:
                if line.startswith('GT'):
                    gcount, acount, tcount, ccount = 0, 0, 0, 0
                    g = np.array([gcount + 1 if nuc == 'G' else gcount for nuc in line[:length]])
                    base = base + g # add this new numpy array
        return base # return the summed result
    

Here are installation instruction for
[`numpy`](http://docs.scipy.org/doc/numpy-1.10.1/user/install.html).

