Python/Django - Best way to avoid UnboundLocalError when a list is empty
I'm using a list to get data from an API.
This list is created with a code like this:
mylist = []
for batch in stream:
for row in batch.results:
data = {}
data["color"] = row.color
data["count"] = row.count
mylist.append(data)
And the list end up being something like:
mylist = [{'color':'red','count':5}, {'color':'blue','count':7}]
And then I send it to the Django template using something like this:
context = {
'mylist' : mylist,
'data' : data,
}
return render(request, 'page.html', context)
This works OK most of the time. But sometimes there is no data to send, so the API doesn't send anything and mylist is empty.
When that happens, I get an error:
UnboundLocalError at /page
local variable 'data' referenced before assignment
I've "solved" it with the following code:
if not mylist:
data = {"error": "no data"}
That removes the error, but seems very "hacky". I don't need that info in my list. If there is no data, I would probably prefer to have the list empty (so I can do an "if" to check if it's empty or not and stuff like that).
Is there a better solution?
Thanks!
(I'm learning Python and Django, so maybe most of my code can be improved, not just the error thing).