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’
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