Implicit lists

Peter Hansen peter at engcorp.com
Thu Jan 30 11:20:21 EST 2003


Dale Strickland-Clark wrote:
> 
> Peter Hansen <peter at engcorp.com> wrote:
> 
> >This is probably a better approach in several ways:
> >
> >def ensureList(thing):
> >  try:
> >    return list(thing)
> >  except TypeError:
> >    return [thing]
> >
> >
> >-Peter
> 
> Except it doesn't work :-)
> 
> >>> list('abc')
> ['a', 'b', 'c']

Of course it does that.  A string is a sequence.  So is
a tuple.  The OP didn't specify what behaviour he wanted
in this case, so "it works" until he clarifies his 
requirements.  :-)

(Your example showed tuples and lists being treated as lists,
but your "in other words" description said "if it isn't already
a list", and that comment includes strings as much as it does
tuples.)

-Peter




More information about the Python-list mailing list