Main Content

Python - listing out the contents of all variables

Archive - Originally posted on "The Horse's Mouth" - 2006-10-21 07:40:02 - Graham Ellis

You can often guess which course I'm giving by the topic of the my daily writing ....

"How do I list out the contents of all variables with names starting v-a-r ... a question from yesterday.

The immediate answer:

# print all variables starting with "var"

sum = 9
var3 = 78
var6 = 99
varsity = 56
variable = "hello"

for name in dir():
 if name.startswith("var"):
  exec("print "+name)


A more thoughtful answer would be to suggest that you might have used a dictionary to store all this information, then you could simply use the keys method ....