Implicit lists

David Eppstein eppstein at ics.uci.edu
Thu Jan 30 14:17:48 EST 2003


In article <5pWO+ks/KzLb089yn at the-wire.com>,
 mwilson at the-wire.com (Mel Wilson) wrote:

> In article <m4di3v4koufdbf4e2pvsanegli2kqt48ch at 4ax.com>,
> Dale Strickland-Clark <dale at riverhall.NOTHANKS.co.uk> 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?
> 
>    I don't see anything wrong with this as it stands; it
> does just what it says and I presume it does just what you
> want.

One problem with it as it stands is that it won't work when lst is a 
simple generator.

how about:

try:
    lst = iter(lst)
except TypeError:
    lst = [lst]

-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/




More information about the Python-list mailing list