# How to iterate over material index using Python

I want to iterate over the material index of material slot and change the value of each material index. How can this be done in Python?

I've tried using the Python shown below, but it doesn't work correctly.

import bpy

object = bpy.context.object
material = object.active_material
for num in range(0, 5):
object.active_material_index = num
else:


The fastest way to loop over the object's materials is through its material_slots attribute. Here's an equivalent code for toggling all object materials shadeless property:

import bpy

for m in bpy.context.object.material_slots:


The only issue I see in your own code is that you're assigning the material to a variable before changing active material index, which renders the latter operation moot. Changing the index before assigning the resulting material to a variable, will yield the result you want.

• this work best, using material_slots seems solve the issue – aditia Oct 16 '13 at 3:36
• doesn't look like it works for you. maybe further testing is needed. – Adhi Oct 17 '13 at 14:11

The error with the script is its not re-assigning material.

Corrected script:

import bpy

object = bpy.context.object
for num in range(0, 5):
object.active_material_index = num
material = object.active_material  # <-- changed line