Is replacing material by slot number the only option? [Pics attached]

Hi guys, I have an object named ‘obj_chess’ which I would like to replace an material called “PaperTopYellow” with “PaperTopRed”.

I used a code as bellow

bpy.data.objects['obj_chess'].data.materials['PaperTopYellow'] = bpy.data.materials['PaperTopRed']

but it did not work so I had to use

bpy.data.objects['obj_chess'].data.materials[3] = bpy.data.materials['PaperTopRed']

to make it work.

However, the problem is that PaperTopYellow may not always be in the third position of the slot. How do I specifically target it by name and replace it?

Thanks

Try something like this:

slotnr = list(i for i, m in enumerate(bpy.data.objects["Cube"].data.materials) if m.name == "papertopyellow")[0]

Thanks for the reply, but it does not seem to work. I run the script of

list = enumerate(bpy.data.objects['Obj_chess'].data.materials)
print(list)

And it prints <enumerate object at 0x116e404c8>

Not sure if I can manipulate the above string to target the one I am aiming for.

for i, m in enumerate(bpy.data.objects['Obj_chess'].material_slots):
    if m.name == 'PaperTopYellow':
       slotnr = i

I have tested this out. This should be the one

Do it the way I wrote it.