Home > Mobile >  TypeError: sequence item 0: expected str instance, list found in python 3
TypeError: sequence item 0: expected str instance, list found in python 3

Time:03-17

I was trying to an take RNA sequence as input and get its respective codons as output.

For example:

Input: AUGGGAACUUCACUACGUAAAUAG

Output: Codons are: AUG, GGA, ACU, UCA, CUA, CGU, AAA, UAG

I coded like this in Python 3.8:

rna = input("Enter the RNA sequence:")
list1 = []
rna = list(rna)

for i in range(len(rna)):
    list2 = []
    list2.append(rna[i : i   3 : 3])
    liststr = "".join(list2)
    list1.append(liststr)

 print(list1)

But, I am getting the error TypeError: sequence item 0: expected str instance, list found. What is the issue with this code?

CodePudding user response:

You're overcomplicating things. You just need to maintain one list, and walk through the string three characters at a time. There's no need to transform a string into a list, or vice versa.

rna = input("Enter the RNA sequence:")
result = []
for i in range(0, len(rna), 3):
    result.append(rna[i:i 3])
print(result)

With the sample input, this produces:

['AUG', 'GGA', 'ACU', 'UCA', 'CUA', 'CGU', 'AAA', 'UAG']

CodePudding user response:

In your code, list2 is a list of lists.

But str.join doesn't work on lists of lists. Consider a minimal example:

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> ''.join(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, list found

You need to join each list into a string. Something like:

list2 = [''.join(lst) for lst in list2]
  • Related