Reputation: 19
so i am trying to parse out a text file by converting it to a list and splitting each item in the list at the space.
i have created a test variable to run this part of the code by itself. my code in the spyder editor:
test = ['NC_009142.1_03_012_002_001 560', 'NC_017586.1_13_009_003_001 555', 'NC_016111.1_13_010_003_001 555']
ListOfLinesParsed = test
PN_List = []
counter_iterative = 0
while counter_iterative < len(ListOfLinesParsed):
PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
counter_iterative += 1
print PN_List
Which returns an error:
runfile(r'/home/jake/.spyder2/.temp.py', wdir=r'/home/jake/.spyder2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-
packages/spyderlib/widgets/externalshell/sitecustomize.py", line 493, in runfile
execfile(filename, namespace)
File "/home/jake/.spyder2/.temp.py", line 7, in <module>
PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
AttributeError: 'NoneType' object has no attribute 'append'
BUT if i enter the commands directly into the terminal i get no error:
testL = []
testL.append(test[0].split()[0])
testL
['NC_009142.1_03_012_002_001']
testL.append(test[1].split()[0])
testL
['NC_009142.1_03_012_002_001', 'NC_017586.1_13_009_003_001']
testL.append(test[2].split()[0])
testL
['NC_009142.1_03_012_002_001', 'NC_017586.1_13_009_003_001', 'NC_016111.1_13_010_003_001']
Shouldn't the 2 things be EXACTLY the same? i don't understand why the one in my script is acting any differently than the terminal commands.
Upvotes: 1
Views: 2400
Reputation: 92
PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
is the issue here. Since .append()
returns None
and you have saved your list to this NoneType
value, on the second iteration, you will get an error because you are trying to use a .append()
on a NoneType
. This is also why you don't get an error in the console because the problem only occurrs the second time you use the above line.
So instead, simply do:
PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
Upvotes: 0
Reputation: 32300
The line
PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
is the problem.
list.append
is an in-place operation, which returns None
, but alters the original list itself. If you assign PN_List
to the result, it becomes None
. If you don't, then your program will run smoothly. This is why when you try appending things without an assignment, you get the expected answer.
Upvotes: 6