Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variables for unknown amount of list items in Python

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading