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?

Best Solution

>>> 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:

or equivalently:

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