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

Creating empty lists base on another list name in Python

The list that will be the name has the form:

 print(my_list)

I get:

[[1, 1], [1, 2], [1, 4], [2, 1], [2, 2], [2, 4], [3, 3], [3, 5], [3, 6], [4, 1], [4, 2], [4, 4], [5, 3], [5, 5], [5, 6], [6, 3], [6, 5], [6, 6]]

I would like to create empty lists based on those pair of numbers, like:

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

for i in my_list:
    'H'+i[0]+i[1] = []

So I would get something like this:

H11 = []
H12 = []
H14 = ...

>Solution :

Dynamic variable assignment as you describe it is discouraged. See How do I create variable variables?, mentioned in the comment by Pranav Hosangadi. Use a dictionary instead, and assign it using dictionary comprehension:

my_lst = [[1, 1], [1, 2], [1, 4], [2, 1], [2, 2], [2, 4], [3, 3],
          [3, 5], [3, 6], [4, 1], [4, 2], [4, 4], [5, 3], [5, 5],
          [5, 6], [6, 3], [6, 5], [6, 6]]

my_dct = { f"H{lst[0]}{lst[1]}": [] for lst in my_lst}

print(my_dct)
# {'H11': [], 'H12': [], 'H14': [], 'H21': [], 'H22': [], 'H24': [], 'H33': [], 'H35': [], 'H36': [], 'H41': [], 'H42': [], 'H44': [], 'H53': [], 'H55': [], 'H56': [], 'H63': [], 'H65': [], 'H66': []}

print(my_dct['H11'])
# []

print(my_dct['H12'])
# []
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