# Python - Assigning vertex weights is extremely slow

Current very slow method (code reduced):

    obj = bpy.context.active_object
vgroups = obj.vertex_groups.new(name="test_layer")

for loop in obj.data.loops:
vindex = obj.data.loops[loop.index].vertex_index


Performance is tested on 1024 x 1024 grid and takes minutes to complete for several weight layers.

My goal is not to assign the same weight value, but different values for each vertex.

I believe I am looking for something like below, which does not exist.

active_object.vertex_groups[group_name].foreach_set()

• As noted in answer below, loop over verts not loops. 8 verts in cube, 24 loops. Also content that loop is obj.data.loops[loop.index] in code above. – batFINGER Dec 7 '20 at 14:35
• @batFINGER that is a good point, I did not think about that and will rewrite to use vertex index instead. I was using loops to get UV data for that vertex, but maybe even that is not necessary. – VSB Dec 7 '20 at 15:01

Usage of loops here is not clear.

You can:

import bpy

obj = bpy.context.active_object
vgroup = obj.vertex_groups.new(name="test_layer")

value = 0.5

for i in range(len(obj.data.vertices)):
vgroup.add( [i], value, 'REPLACE')


We add vertices to a group, using their indexes.

The documentation is here:

Add vertices to the group

Parameters
index (int array of 1 items in [-inf, inf]) – Index List
weight (float in [0, 1]) – Vertex weight
type (enum in ['REPLACE', 'ADD', 'SUBTRACT']) –
Vertex assign mode
REPLACE Replace, Replace.

• I am using loops due to other processes in the function. The method you provided is the same one I use and is very slow. For example to batch set vertex colors this should work active_object.data.vertex_colors[0].data.foreach_set(new_color_set) – VSB Dec 6 '20 at 22:23
• No need for loop with constant value (value = 0.5 as coded above) vg.add(range(len(obj.data.vertices)), value, 'REPLACE') – batFINGER Dec 7 '20 at 14:31