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

How can I iterate through this list with modular variables

Let’s say I have one file called colours.py that contains this:

black = (0, 0, 0)
aqua = (0, 255, 255)

And my main.py file contains:

import colours

colour_list = ['black', 'aqua']

for i in colour_list:
    colour = colours.i[0]
    print(colour)

I get AttributeError: module ‘colours’ has no attribute ‘i’

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

How do I iterate through it to access the first index of each variable?

>Solution :

You can’t reference variables with the name as string like you do here (or you can, but it’s using some obscure mechanism of python like reading variables from globals instead by reference).

Instead, it’s better if you import the variables and use directly their references.

from colours import black, aqua

colour_list = [black, aqua]

for colour in colour_list:
    print(colour) #For the complete variable 
    print(colour[0]) #For the first index
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