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>Look into the <a href="https://docs.python.org/3/library/statistics.html" rel="nofollow"><code>statistics</code></a> module.
You'll find all kinds of measures of averages and spreads.</p>

<p>You'll get the length of any sequence using <code>len</code>.</p>

<p>In your case, you'll want to map the sequences to their lengths:</p>

<pre><code>from statistics import stdev

with open("seq.txt") as f:
    lengths = [len(line.strip()) for line in f]

print("Number of sequences:", len(lengths))
print("Standard deviation:", stdev(lengths))
</code></pre>

<p><strong>edit:</strong> Because it was asked in the comments: Here's how to cluster the instances into different files depending on their lengths:</p>

<pre><code>from statistics import stdev, mean
with open("seq.txt") as f:
    sequences = [line.strip() for line in f]
lengths = [len(sequence) for sequence in sequences]

mean_ = mean(lengths)
stdev_ = stdev(lengths)

with open("below.txt", "w") as below, open("above.txt", "w") as above, open("normal.txt", "w") as normal:
    for sequence in sequences:
        if len(sequence) &gt; mean+stdev_:
            above.write(sequence + "\n")
        elif mean+stdev_ &gt; len(sequence &gt; mean-stdev_: #inbetween
            normal.write(sequence + "\n")
        else:
            below.write(sequence + "\n")
</code></pre>

python string list python-3.x math