I have been here for a couple of months learning python from examples, but the time has come to ask one for myself.
I am currently working on a script here at work that scrapes the job queue from a website & sends a notification if a certain condition exists.
The hard part is out of the way & I have the results being split into nested lists, but when I try & search for a specific condition I get an error if it doesn’t exist.
customers = [['00:00:02', 'S3'], ['00:00:46', 'S2']]
[item for item in customers if 'S2' in item[1]]
print('%s %s') % (item[1], item[0])
The condition above works well if there is a ‘S2’ condition, but if there isn’t (because the page im scraping from may not have one) I get an error:
UnboundLocalError: local variable 'item' referenced before assignment
This is probably a very basic question but how can I stop this error from occurring?
In python 2.x, the variables used inside of list comprehensions (here,
item) leaks out of the list comprehension into the surrounding scope. Using it afterwards is not typically a good idea, or clear code. Try something like this: