I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the
I like Andrei Vajna's suggestion of hasattr(var,'__iter__')
. Note these results from some typical Python types:
>>> hasattr("abc","__iter__")
False
>>> hasattr((0,),"__iter__")
True
>>> hasattr({},"__iter__")
True
>>> hasattr(set(),"__iter__")
True
This has the added advantage of treating a string as a non-iterable - strings are a grey area, as sometimes you want to treat them as an element, other times as a sequence of characters.
Note that in Python 3 the str
type does have the __iter__
attribute and this does not work:
>>> hasattr("abc", "__iter__")
True
This seems like a reasonable way to do it. You're wanting to test if the element is a list, and this accomplishes that directly. It gets more complicated if you want to support other 'list-like' data types, too, for example:
isinstance(input, (list, tuple))
or more generally, abstract away the question:
def iterable(obj):
try:
len(obj)
return True
except TypeError:
return False
but again, in summary, your method is simple and correct, which sounds good to me!