iterating over a variable which could be None, a single object, or a list
Arnaud Delobelle
arnodel at googlemail.com
Thu Nov 27 14:53:07 EST 2008
"adam carr" <adambriancarr at gmail.com> writes:
> Denis kindly provided the following code which does this well:
>
> def mkiter( x ):
> """ list -> list, el -> [el], None -> []
> usage: for x in mkiter( func returning list or
> singleton ): ...
> """
> return (x if hasattr( x, "__iter__" ) # list tuple ...
> else [] if x is None
> else [x]
> )
>
> # test --
> print mkiter( 1 )
> print mkiter( (2,3) )
> print mkiter( None )
If you want to go this way, then why not write it simply:
def mkiter(x):
if hasattr(x, '__iter__'):
return x
return [] if x is None else [x]
--
Arnaud
More information about the Python-list
mailing list