Variable depth of nesting

Jacek Generowicz jmg at ecs.soton.ac.uk
Wed Feb 7 06:44:15 EST 2001


Is it somehow possible to write loops with variable nesting depths?

For example, I would like to write something like the function
outlined below without having to use the if clauses. Particularly, I
would like to make it work for a GENERAL length of list_of_lists.

def hmm ( list_of_lists ):
    if len( list_of_lists ) == 1:
        for x in list_of_lists[0]:
            # do something
        return

    if len( list_of_lists ) == 2:
        for x in list_of_lists[0]:
            for y in list_of_lists[1]
            # do somehting
        return

    if len( list_of_lists ) == 3:
        for x . . . :
            for y . . . :
                for z . . . :
                    # do something
        return
                    
    if len( list_of_lists ) == 4:

    #etc.
    #etc.


Alternatively, how about list comprehensions with variable order:


def hmm ( l ):
    if len( l ) == 1:
        return [ x for x in l[0] ]

    if len( l ) == 2:
        return [ (x,y) for x in l[0] for y in l[1] ]

    if len( l ) == 3:
        return [ (x,y,z) for x in l[0] for y in l[1] for z in l[2] ]
                    
    #etc.
    #etc.


Any ideas ?

Thanks,

Jacek



More information about the Python-list mailing list