0

What I want to do:

  • After having declared some variables, a list of the names of those variable is defined. Then, I would like to delete the variables using their names contained in the list.

Here is a simple reproducible example :

# variables are defined
variable_a = "first elt"
variable_b = "second elt"

# for some reasons, a list of variable names is defined and filled
list_of_variables_names = ['variable_a', 'variable_b']

# then variables are to be deleted
# using the list of variable names

What I tried, which obviously, does not work

for variable in list_of_variables_names:
   del variable

The above code does not delete variables, because elements of the list are name of variables (strings inside '').

an ch
  • 59
  • 5
  • I've answered a couple questions like that, but not anymore, since they get downvoted always. You can use `f-string`, `eval` combination to do that. However you should NOT try to do that. Use different datastructure e.g. a `dict` and modify its keys/values. You should NOT modify variables by their name like that. – Gameplay Jan 12 '23 at 11:47
  • Thaks @Gameplay. Sorry for my question. But, none of solutions listed answer to my question. I mean: sure, it would be better to build a dict. But, it could happen. it comes in a list afterwards. Like when you try to list all variables defined of a notebook and get the memory used for each variable ... Then, using this list to delete the too much memory usage variable, is something that could happend .... – an ch Jan 12 '23 at 12:29
  • Having code that dynamically deletes a dynamically generated list of variables seems like a recipe for a bug. You wouldn't even know what variables are being deleted. – John Coleman Jan 12 '23 at 12:54

0 Answers0