Snippet for cleaning vertex groups

Here is a little snippet from a vacuum cleaner addon I’m putting together that I thought I’d post because I’ve found it pretty handy and couldn’t find a quick way to do this

Sometimes when you join objects and forget to clear vertex groups first you end up with a whole lot of unnecessary vgroups, and when weight painting often end up with a whole lot of zero weight vertices…

Went the loop thru verts first going thru groups then verts would give a nicer vert list to delete but it seemed to me that this way involved going thru verts only once.

import bpy

TOL = 0.001

meshobj = bpy.context.active_object
mode = meshobj.mode

# remove unwanted vertex-groups
# remove vertex groups that aren't in the keep collection
keep = ["jaw","upper_mouth","lower_mouth","eyelid.L","head"]

for vg in meshobj.vertex_groups:
    if not in keep:
# remove all verts with weight less than TOL in vertex groups.        
mesh =

for vert in mesh.vertices :
    for vertgroup in vert.groups:
        verts_toremove = []
        if vertgroup.weight < TOL:
        if len(verts_toremove):