Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: “List.append = ‘list’ object attribute ‘append’ is read-only”

I’m trying to write a response from a Solr server to a CSV file. I’m pretty new to python and have been given code to modify. Originally the code looked like this ...

for doc in response.results:
    status = json.loads(doc['status'])

The script runs and prints the correct information. But it only every prints one result (last one). I think this is because the loop constantly writes over the varible 'status' until its worked through the response.

After some reading I decided to store the information in a list. That way i could print the information to seprate lines in a list. I created an empty list and changed the code below -

for doc in response.results:
    list.append = json.loads(doc['status'])

I got this response back after trying to run the code -

`AttributeError: 'list' object attribute 'append' is read-only`.

Where am I going wrong? Is a list not the best approach?

like image 791
Chris Chalmers Avatar asked Feb 20 '12 19:02

Chris Chalmers


2 Answers

>>> list.append
<method 'append' of 'list' objects>

You're trying to modify the append method of the built-in list class!

Just do

docstats = []
for doc in response.results:
    docstats.append(json.loads(doc['status']))

or equivalently:

docstats = [json.loads(doc['status']) for doc in response.results]
like image 145
Useless Avatar answered Sep 19 '22 02:09

Useless


I'm not sure what you are trying to do.

I guess you haven't created a list variable. list is a python's builtin class for lists, so if there's no variable to mask it, you'll access that. And you tried to modify one of it's propterties, which is not allowed (it's not like ruby where you can monkey-patch anything).

Is this what you want? :

l=[]
for doc in response.results:
    l.append(json.loads(doc[‘status’]))
like image 44
Karoly Horvath Avatar answered Sep 18 '22 02:09

Karoly Horvath