Using bmesh.
Similarly to this answer loop thru the face loops and set the associated vertex to a color based on its index. result on default uv_sphere, cube and torus
import bpy
import bmesh
context = bpy.context
mesh = context.object.data
bm = bmesh.new()
bm.from_mesh(mesh)
color_layers = bm.loops.layers.color
color_layer = color_layers.get("color") or color_layers.new("color")
L = len(bm.verts) - 1
for face in bm.faces:
for loop in face.loops:
x = loop.vert.index / L
print("Vert:", loop.vert.index)
loop[color_layer] = (x, x, x, 1)
bm.to_mesh(mesh)
Note: for large meshes could make a a look up table for vert and color to avoid calculating for same vert per face loop.
LUT = {v : v.index / L for v in bm.verts}