# How can i get the weight for all vertices in a vertex group?

I have created this function to get the weights from a group:

def get_weights(ob, vgroup):
weights = []
for index, vert in enumerate(ob.data.vertices):
for group in vert.groups:
if group.group == vgroup.index:
weights.append([index, group.weight])
return weights


Is there any better more efficient way to do this?

• Is this spesific to any particular mesh api? RNA / BMesh? – ideasman42 Feb 13 '16 at 11:30
• no, i just want to know how this can be done better and more efficient in which way ever. – Gaia Clary Feb 13 '16 at 11:37

For The RNA mesh API, your example is quite good, one minor change you can make is to break once the group index is found.

Instead of making a large list, you could use a generator function, this can save memory for the cases you can iterate over the elements, and be converted to a list or tuple if you need, it has the same worst-case time, but in practice will often save some looping.

import bpy
obj = bpy.context.object

def get_weights(ob, vgroup):
group_index = vgroup.index
for i, v in enumerate(ob.data.vertices):
for g in v.groups:
if g.group == group_index:
yield (i, g.weight)
break

import bpy
obj = bpy.context.object
vgroup = obj.vertex_groups[0]

# iterate over index, weights
for i, w in get_weights(obj, vgroup):
print(i, w)

# if you need as a list...
weights = list(get_weights(obj, vgroup))
print(weights)


Note, in some similar cases to this, you can use list-comprehension, however having to check the vertex is in the group causes the checks within the list-comprehension to become quite convoluted, so best avoid in this case.