Go back from the selected node and get the parent node.
Maya Cmds version
import maya.cmds as cmds
def get_parent(node):
    parent = cmds.listRelatives(node, parent=True, path=True)
    if parent:
        yield parent
        for p in get_parent(parent):
            yield p
for node in get_parent(cmds.ls(selection=True)):
    print node
PyMel version
import pymel.core as pm
def get_parent(node):
    parent = pm.listRelatives(node, parent=True)
    if parent:
        yield parent
        for p in get_parent(parent):
            yield p
for node in get_parent(pm.selected()):
    print node
If you select null1 and run the script, you will get the following results:

[nt.Transform(u'group1')]
[nt.Transform(u'group2')]
[nt.Transform(u'group3')]
        Recommended Posts