Implicit lists

holger krekel pyth at devel.trillke.net
Thu Jan 30 10:07:42 EST 2003


Dale Strickland-Clark wrote:
> In many places, often small utility functions, I find myself using the
> form:
> 
> lst = maybeAnArg
> if type(lst) not in (list, tuple)
>     lst = [lst]
> for x in lst:
>     whatever

hmmm. Maybe with a general-purpose 

    def elems(*args):
        l = []
        for arg in args:
            try: l.extend(arg)
            except TypeError: l.append(arg)
        return l
            
you might like to write:

    for x in elems(lst):

and use it also to iterate consecutively over the
elements of more than one list or value:

    for x in elems(lst1, lst2, 42):

HTH,

    holger





More information about the Python-list mailing list