Type checking would be a great way to achieve this. How would you otherwise decide if the input was a list or a string?.
You could make a function which tests if the input is a list or a string and returns appropriately and handles the rest as you see fit. Something along the lines of
>>> def convert_to_tuple(elem):
if isinstance(elem, list):
return tuple(elem)
elif isinstance(elem, basestring):
return (elem,)
else:
# Do Something
pass
>>> convert_to_tuple('abc')
('abc',)
>>> convert_to_tuple(['abc', 'def'])
('abc', 'def')
You could only check for strings too, (Assuming Python 2.x, replace basestring
with str
in Py3)
>>> def convert_to_tuple(elem):
if isinstance(elem, basestring):
return (elem,)
else:
return tuple(elem)
>>> convert_to_tuple('abc')
('abc',)
>>> convert_to_tuple(('abc', 'def'))
('abc', 'def')
>>> convert_to_tuple(['abc', 'def'])
('abc', 'def')
Converting the function to a one liner is possible too.
>>> def convert_to_tuple(elem):
return (elem,) if isinstance(elem, basestring) else tuple(elem)