I have a series of variables called pic1, pic2, pic3 etc. I want to create a list of all the variables that begin with “pic”
the long way would be as follows
JavaScript
x
3
1
piclist = [pic1,pic2,pic3, ]
2
3
there must be a shorter way?
thanks in advance
Advertisement
Answer
I am assuming that the variables are defined in module level. If yes you can use globals()
which returns a dictionary containing the current scope’s global variables
JavaScript
1
6
1
>>> pic1 = 1
2
>>> pic2 = 2
3
>>>
4
>>> [globals()[key] for key in globals() if key.startswith("pic")]
5
[1, 2]
6