iterating over a variable which could be None, a single object, or a list

adam carr adambriancarr at gmail.com
Thu Nov 27 13:40:36 CET 2008


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 )



More information about the Python-list mailing list