admin管理员组

文章数量:1202948

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?

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?

Share Improve this question edited Jan 21 at 7:31 Anerdw 1,8853 gold badges15 silver badges37 bronze badges asked Jan 21 at 5:40 DarwinDarwin 2,0371 gold badge25 silver badges31 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 1

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.

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

本文标签: pythonTypeError 39Seq39 object does not support item assignmentStack Overflow