# Python: Assign selected faces to vertex group

I have a script that selects some random faces and splits them. I would like to add the selection to a vertex group. I can't get my script to assign the selection to a vertex group. Thank you for the help.

            sub2 = 0
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.select_random(percent=55, seed=10, action='DESELECT')
bpy.ops.mesh.split()
group = context.object.vertex_groups.new()
group.name = ("Island" + str(sub2))
#group.add(bpy.data.objects.data.verts, 1.0, 'ADD')
bpy.ops.object.vertex_group_assign()


## 1 Answer

You have missing "bpy" on line 4, so it should be:

group = bpy.context.object.vertex_groups.new()


Don't forget to import bpy:

import bpy


## Whole script:

import bpy
sub2 = 0
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.select_random(percent=55, seed=10, action='DESELECT')
bpy.ops.mesh.split()
group = bpy.context.object.vertex_groups.new()
group.name = ("Island" + str(sub2))
#group.add(bpy.data.objects.data.verts, 1.0, 'ADD')
bpy.ops.object.vertex_group_assign()

• Oh man, something so simple. It was throwing me off because it would still create the group without the bpy if front of context. Thank you very much for your help! – admbro Oct 17 '17 at 15:27
• Use Window -> Toggle System Console to see the actual error messages and the line number where your script fails. In this case, you would get "context is incorrect" error. – Jan Kadeřábek Oct 17 '17 at 16:59