0

To check if a global variable exists (and if so, delete it) I have been using this method:

if 'y' in globals():
     y.remove()

But I get the following error:

ValueError: list.remove(x): x not in list

This method has worked for me in the past, I don't understand why the if statement accepts the statement as true, which implies 'y' exists, and then tells me 'y' does not exist. Is there a fix or even a completely different method of doing this? For context, 'y' is part of a scatter plot on a matplotlib.figure plot, which is embedded in a canvas for a tkinter GUI.

CWoody00
  • 5
  • 1
  • I am assuming `y` a list that is why you are getting that error. `remove` is an attribute for lists in python – It_is_Chris Mar 18 '22 at 15:58
  • @Matiiss ignore me, ucczs is correct :) – konstanze Mar 18 '22 at 16:02
  • Just as a side-note - if you are learning Python I would suggest avoiding `global` altogether. I has it's use-cases, but too often it is a shortcut that will bite you later. – alex Mar 18 '22 at 16:03
  • @alex `global` or `globals`? – Matiiss Mar 18 '22 at 16:05
  • @Matiiss both actually. Learn the scopes first, then fiddle with `global`/`globals()` – alex Mar 18 '22 at 16:08
  • @alex I usually try and avoid global variables but for this specific project they have proved to the easier method unfortunately – CWoody00 Mar 18 '22 at 16:15
  • Sure, let me just link this answer _[Why are global variables evil?](https://stackoverflow.com/a/19158418/1185254)_ for reference. – alex Mar 18 '22 at 16:18

1 Answers1

6

If you want to delete a variable you should use del:

if 'y' in globals():
    del y
ucczs
  • 609
  • 5
  • 15
  • This stopped the error, however it does not remove ```y``` from the scatter graph like before and I get duplicates – CWoody00 Mar 18 '22 at 16:09
  • 1
    Ok weirdly the solution is to use ```del y``` for part of my code but keep ```y.remove()``` for other parts, so thank you for the solution. – CWoody00 Mar 18 '22 at 16:22