Python – make_iterable


Run into an issue with passing in an object to a function, but its type is changeable? Maybe you usually have multiple returns from another function formatted in an array or list or tuple, but in some cases it’s just a single value. This is a quick little check/changer to make sure your object is iterable, or recast it into a list for a simple way to dodge the dreaded TypeError!


    def make_iterable(item):
        '''Checks if item is iterable - if not it casts it into a list containing [item].
            **********ARGUMENTS**********
            :param item: object to check
            **********RETURNS**********
            :return: item if item is iterable, or iterable version of item as [item]
            '''
        try:
            iter(item)
        except TypeError:
            item = [item]
        return item
    
, ,