Selecting vertices of a vertex group

I am aware that if in edit mode you can select all the vertices of the vertex group with

bpy.ops.object.vertex_group_select()

If more than one vertex group is defined the one selected is taken.
What I want to do however is to collect all the vertices of a vertex group of an object in a list. It should work both in object and edit mode and irrelevant if the object is selected.
I’m aiming at a script that loops through some objects and updates all the vertices that belong to a vertex group.

The layout of the groups and the values are a little odd.

To find out if an Object has a vertex group, you can iterate Object.vertex_groups to see if it has a group with the correct name. Once you know the Object has the group then you can iterate Mesh.vertices and each vertex will have Vertex.groups that have an index back to the Object group.

i.e.


import bpy

# find the index of the target group
for obj in bpy.data.objects:
  if type(obj.data) != bpy.types.Mesh:
    continue

  # This is an Object with a Mesh, see if it has the supported group name
  groupIndex = -1
  for i in range(0, len(obj.vertex_groups)):
    group = obj.vertex_groups[i]
    if group.name == "Test":
      groupIndex = i

  print("Checking %s for assigned vertices." % (obj.name))

  # Now access the vertices that are assigned to this group
  mesh = obj.data
  for v in mesh.vertices:
    
    for vertGroup in v.groups:
      if vertGroup.group == groupIndex:
      
        print("Vertex %d is part of group."%(v.index))    

I suggest that you find a way to work around your requirements that this run in both Object and Edit mode. Blender seems to use some copy-in/copy-out strategies when toggling between Object and Edit mode. The Python API generally works best for operations like this when run from Object mode.

Attachments

vertgroups.blend (440 KB)

That should work thanks. Sometimes it’s hard to bend the mind in the right way :smiley:
I will have check this out in my context.

Thanks