Skip to content
Advertisement

Creat a list of variables with a specific prefix [closed]

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

piclist = [pic1,pic2,pic3,...]

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

>>> pic1 = 1
>>> pic2 = 2
>>>
>>> [globals()[key] for key in globals() if key.startswith("pic")]
[1, 2]
Advertisement