Implicit lists

A. Lloyd Flanagan alloydflanagan at attbi.com
Thu Jan 30 14:24:23 EST 2003


Dale Strickland-Clark <dale at riverhall.NOTHANKS.co.uk> wrote in message news:<m4di3v4koufdbf4e2pvsanegli2kqt48ch at 4ax.com>...
> 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):
   try:
      x[0]
   except TypeError:
      return [x]
   return x

or just:

try:
     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