How to calculate each string length that belongs to a list of strings by python?
<p>Suppose I have a file with <code>n</code> DNA sequences, each one in a line. I need to turn them into a list and then calculate each sequence's length and then total length of all of them together. I am not sure how to do that before they are into a list. </p>

<pre><code># open file and writing each sequences' length
f= open('seq.txt' , 'r')
for line in f:
    line= line.strip()
    print (line)
    print ('this is the length of the given sequence', len(line))

# turning into a list:  
lines = [line.strip() for line in open('seq.txt')]
print (lines)
</code></pre>

<p>How can I do math calculations from the list? Ex. the total length of all sequences together? Standard deviation from their different lengths etc.</p>

<p>You have already seen how to get the list of sequences and a list of the lengths using append.</p>

<pre><code>    lines = [line.strip() for line in open('seq.txt')]
    total = 0
    sizes = []
    for line in lines:
       mysize = len(line)
       total += mysize
       sizes.append(mysize)
</code></pre>

<p>Note that you can also use a for loop to read each line and append to the two lists rather than read every line into lists and then loop through lists. It is a matter of which you would prefer.</p>

<p>You can use the statistics library (as of Python 3.4) for the statistics on the list of lengths.</p>

<p><a href="https://docs.python.org/3/library/statistics.html" rel="nofollow">statistics â Mathematical statistics functions</a></p>

<blockquote>
  <p>mean()    Arithmetic mean (âaverageâ) of data.    median()    Median (middle
  value) of data.    median_low()   Low median of data.<br>
  median_high() High median of data.    median_grouped()    Median, or 50th
  percentile, of grouped data.    mode()    Mode (most common value) of
  discrete data.    pstdev()    Population standard deviation of data.<br>
  pvariance()   Population variance of data.    stdev() Sample standard
  deviation of data.    variance()  Sample variance of data.</p>
</blockquote>

<p>You can also use the answers at <a href="http://stackoverflow.com/questions/15389768/standard-deviation-of-a-list">Standard deviation of a list</a></p>

<p>Note that there is an answer that actually shows the code that was added to Python 3.4 for the statistics module. If you have an older version, you can use that code or get the statistics module code for your own system.</p>

python string list python-3.x math