I have a list with unknown amount of items. For example, the list could be something like ["d", "e", "f", "g"] or ["15", "27", "o"], but with a larger amount of items. I want to know how to take a list and assign it to a variable (eg. var1 = "d", var2 = "e" …), and I want the program to print the variable names and values.
I know that I need to use the len() function, but don’t know where to got from there. I want it so that I don’t need to hardcode the variables, eg. hardcoding from var1 to var500 is obviously not a feasible option. Can I do something similar to var_name = var+var_num? Thanks in advance!
>Solution :
If I understood your point correct, you can use dictionary, and assign key / value pair, where key is string value + index and value is value.
enumerate function is used to iterate through the list while also generating an index.
my_list = ["d", "e", "f", "g"]
variables = {}
for i, item in enumerate(my_list, start=1):
var_name = f"var{i}"
variables[var_name] = item
for var_name, value in variables.items():
print(f"{var_name} = {value}")