Reputation: 2057
I have a Seq
object in Biopython (1.85), and I want to change its third element to A
. When I run this code:
from Bio.Seq import Seq
seq = Seq('CCGGGTTAACGTA')
seq[2]= 'A'
I get this error:
TypeError: 'Seq' object does not support item assignment
How can I properly reassign the element?
Upvotes: 1
Views: 70
Reputation: 3096
you could do :
from Bio import __version__
print('\nBiopython Version ---> ', __version__)
from Bio.Seq import Seq, MutableSeq
seq = Seq('CCGGGTTAACGTA')
print(seq)
print(seq[2])
seq = seq.replace(seq , (''.join([seq[i] if i != 2 else 'A' for i in range(len(seq))])))
print(seq)
print(seq[2])
output:
Biopython Version ---> 1.85
CCGGGTTAACGTA
G
CCAGGTTAACGTA
A
but looks like 2-3 times slower than using MutableSeq
Upvotes: 0
Reputation: 1987
Biopython sequences are immutable, so you cannot perform item assignment on them the way you could a list. You're looking for a MutableSeq
instead. If you already have a Seq
, you can convert it into a MutableSeq
by passing it into the constructor:
from Bio.Seq import Seq, MutableSeq
seq = Seq('CCGGGTTAACGTA')
mut_seq = MutableSeq(seq)
print(mut_seq) # CCGGGTTAACGTA
mut_seq[2] = 'A'
print(mut_seq) # CCAGGTTAACGTA
Of course, you can also just construct your sequence as a MutableSeq
directly if the situation allows for it.
from Bio.Seq import MutableSeq
mut_seq = MutableSeq('CCGGGTTAACGTA')
print(mut_seq) # CCGGGTTAACGTA
mut_seq[2] = 'A'
print(mut_seq) # CCAGGTTAACGTA
And once you have a MutableSeq
, you can convert it into a plain immutable Seq
the same way you would do the reverse:
seq = Seq(mut_seq)
Note that in earlier versions, you could've performed these conversions via the Seq.tomutable
and MutableSeq.toseq
methods. However, these methods no longer exist in v1.85, being deprecated in 1.79 and removed in 1.81.
Upvotes: 1
Reputation: 2057
I used MutableSeq
module
from Bio.Seq import MutableSeq
seq = MutableSeq('CCGGGTTAACGTA')
seq[2] = 'A'
Another example:
from Bio.Seq import Seq, MutableSeq
seq1 = Seq("ACGT")
seq2 = Seq("ACGT")
mutable_seq = MutableSeq("ACGT")
print(seq1 == seq2) #True
print(seq1 == mutable_seq) #True
print(seq1 == "ACGT") #True
Upvotes: 0