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