Implicit lists

A. Lloyd Flanagan alloydflanagan at
Thu Jan 30 20:24:23 CET 2003

Dale Strickland-Clark <dale at> wrote in message news:<m4di3v4koufdbf4e2pvsanegli2kqt48ch at>...
> 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
> Has anyone got a neater way of doing this?

In python, if you ever try to explicitly check the type of something,
you're almost certainly doing it wrong.  You don't care if the thing
is a list, usually, you want to know if it's a sequence, whether a
list, tuple, set, or some user-defined type.  So try subscripting it:

def aslist(x):
   except TypeError:
      return [x]
   return x

or just:

     mangle = [x for x in lst if whatever]
except TypeError:
     mangle = [x for x in [lst] if whatever]

More information about the Python-list mailing list