# 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:
# do something
return

if len( list_of_lists ) == 2:
for x in list_of_lists:
for y in list_of_lists
# 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 ]

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

if len( l ) == 3:
return [ (x,y,z) for x in l for y in l for z in l ]

#etc.
#etc.

Any ideas ?

Thanks,

Jacek

```