How to select a vertex of a mesh

There has to be something simple that i am missing. I am trying to select some vertices of a mesh but i cannot get this to work.

obj = bpy.context.active_object
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.select_all(action = 'DESELECT')
obj.data.vertices[0].select = True
print('NUMBER OF SELECTED VERTS: ',obj.data.total_vert_sel)

For some reason the total_vert_sel will return 0. I would assume that setting the select property of a vertex to True will select the vertex but no luck so far. Can anyone tell me what i am missing?

I think it is because you are mixing code techniques. You are using the bpy.ops tools to manage the objects then you go behind the scenes and manipulate the datablock directly. bpy.ops does not know you did that. Try one way or the other.


obj = bpy.data.objects.get("Cube")
for v in obj.data.vertices:
    v.select = False
obj.data.vertices[0].select = True

or

Instead of manipulating the vertex select flag directly, find a bpy.ops version of that same operation and use it instead.

Check out the Gotchas Documentation. There is a section on no updates after setting value, meshes and modes.

i found that if i create a bmesh object then i can select the verts. Here is a sample of how i got it to work.


obj_mesh = bpy.context.active_object
import bmesh
mesh = obj_mesh.data
bm = bmesh.new()
bm.from_mesh(mesh)
for v in bm.verts:
    v.select = False


bm.verts[0].select = True

bm.to_mesh(mesh)
bm.free()

you could use bmesh.from_edit_mesh to avoid having to create a new bm and writing it back, but requires editmode. from_edit_mesh will wrap the actual mesh there’s practically no overhead