How can I fix this TypeError: append() takes exactly one argument (3 given) for this specific example?

Viewed 2017

I´m trying to read a text file that is in columns formats, here is how it looks like:

AVP78031.1_NA   18 NLTG   0.7234     (9/9)   ++
AVP78031.1_NA   28 NYTN   0.7796     (9/9)   +++
AVP78031.1_NA   31 NSSQ   0.5689     (6/9)   +
AVP78031.1_NA   62 NVSW   0.7594     (9/9)   +++
...

My goal is to take the first, second, and fourth columns. So for that, I use a for loop to take the text/values in each column. Here are the lines of

S_align = AlignIO.read("S_aa_MSA_pathogenic.fasta", "fasta")
with open("BatlikeSARS_N.csv") as f:
    lines = f.readlines()
    #print(lines)
result=[]
for x in lines:
### HERE IS THE TYPE ERROR
    result.append(x.split(" ")[0],[1],[3])
    #print(len(result))
    print(result)

This code gives me this error:

TypeError: append() takes exactly one argument (3 given)

I partially understand the error, because I suppose that the split (0, 1, and 3) are correct; however, it's obvious that something is wrong. Any idea to chance the script or add some lines is welcome!

3 Answers

You want to do:

for x in lines:
    splitted = x.split(" ")
    result.append([splitted[0], splitted[1], splitted[3]])
    ...

This will create a list initialized to have three items, the 1st, 2nd and 4th items in the split line x, and then append this new list to the result.

In the sample you provided, you are effectively calling the append() method with 3 arguments:

  1. the first split item x.split(" ")[0]
  2. a new list initialized to [1]
  3. a new list initialized to [3]

Keep in mind that the comma is used to separate positional arguments for a function/method call.

First of all x.split(" ")[0],[1],[3] is not correct, and secondly, you can't pass more than one argument to .append(). I assume that you are trying to create a nested list. Try something like

cols = x.split(" ")
result.append([cols[0], cols[1], cols[3]])

Ok, the problem here is that

result.append(x.split(" ")[0],[1],[3])

tries to append 3 values to result:

1º value: x.split(" ")[0]

2º value: [1]

3º value: [3]

But append only takes 1 value and it is the value that is going to put at the end of the list so, the right way to do it would be like this:

x = x.split("   ")   # Split the line
x.pop(2)             # Remove the 3rd element
x.pop(3)             # Remove the 3rd element again
result.append(x)     # Append the line

In this case I suppose that the separator is " " (3 spaces) that is why in split i put " "

Related