Implicit lists

Peter Hansen peter at engcorp.com
Thu Jan 30 10:37:52 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
[...] 
> In other words, I want to be able to treat an argument of arbitrary
> type as a list of 1 if it isn't already a list.
> 
> Has anyone got a neater way of doing this?

Define "neater". :-)

This is probably a better approach in several ways:

def ensureList(thing):
  try:
    return list(thing)
  except TypeError:
    return [thing]


-Peter




More information about the Python-list mailing list