Sorry, I'm new to programming so excuse me if my question is lackluster. I want to load these images through the use of a list and a for loop but I keep getting this list error where it says the list indices must be integers or slices. How can I fix this?
code:
Images = ['K2', 'G2', 'S2', 'N2', 'L2', 'R2', 'B2', 'P2']
p = []
for n in Images:
p.append(pygame.image.load(os.path.join('Assets', 'Pieces (set 1)', Images[n] '.png')))
error:
p.append(pygame.image.load(os.path.join('Assets', 'Pieces (set 1)', Images[n] '.png')))
TypeError: list indices must be integers or slices, not str
CodePudding user response:
See for Statements. Either
for i in range(len(Images)):
p.append(pygame.image.load(os.path.join('Assets', 'Pieces (set 1)', Images[i] '.png')))
or
for name in Images:
p.append(pygame.image.load(os.path.join('Assets', 'Pieces (set 1)', name '.png')))
CodePudding user response:
Consider what values n take here: for n in Images:. n will loop through the elements in Images, thus n is of type str. You cannot use a string as an index to a list Images[n]. You probably meant to construct the loop like this: for n in range(len(Images)). Then n will be integers from 0 to len(Images) - 1.
