You can use locals()
for that or even globals()
depending on the scope. For you that scope now seems to be global as the variable is outside of the function, so:
for key, val in dict(globals()).items():
if "list" in key:
print(key, val)
The problem with that is that mostly you don't want that because it'll contain other symbols (functions, variables, modules, etc), so it's wiser to instead create a separate dictionary for that and read from it.
myvalues = {
"list1": [1, 2, 3],
"list2": [4, 5, 6],
"list3": [7, 8, 9]
}
def get_list(number):
return myvalues[f"list{number}"]
print(get_list(1))
Note: as others point out in the comments, list
is already a thing in Python, so it's not wise to use it as a name if you don't know what you are doing. For example once you do this, you can't no longer (in that scope) access list
as a type and e.g. convert anything to a list other way than via list comprehension or other hack because you've basically removed the only (public) thing that is capable to do that.
Note 2: eval()
is evil if not used properly. You don't need it for this use case. If anything, most of the cases can be handled by literal_eval()
, though I think that one wouldn't help here.