Though it gives me duplicated result of certain groups, is this the best way to approach this?
I am using Group_ as a generic naming and hence my reluctance to use Group_*, in case you are wondering…
I’m not sure exactly what you are trying to accomplish. Are you trying to get all transforms that don’t have a shape under them, or only transforms that have another transform as a child? Given this hierarchy, what would you want returned?
|--Group_1
|--Group_2
|--pCube1
|--Group_3
Groups 1-3, or just groups 1 & 2?
And what if you have a mesh transform under another mesh transform?
Why not force group nodes to have a consistent suffix like _GRP and that way you can get all groups using *_GRP? That way you don’t have to worry about figuring out how to determine a group based on its relatives.
As capper mentioned, there are a couple of scenarios that are possible depending on what exactly you want. However, this snippet of code should give you enough to get going…
import pymel.core as pm
# -- This will give you all transform nodes (but note that a mesh has a transform node too - so it still gets thats!
all_groups = pm.selected()[0].getChildren(ad=True, type='transform')
print(all_groups)
# -- If you do not want the transform nodes that have shapes, you can do this...
all_groups = [g for g in all_groups if not g.getShapes()]
print(all_groups)
Because a mesh is just a shape node, and therefore resides under its own transform node just getting all the children of type ‘transform’ will also return the transform node for each mesh - which may, or may not be what you want.
If that is not what you want you can use the second part which goes through the list of transform nodes and only takes the transforms that have no direct childrens of a shape type - meaning we only get nodes that are what we see as ‘groups’ in the outliner.