Python: Create list from function that returns single item or another list
<p>(Python 3.5). </p>

<p><strong>Problem Statement:</strong> Given a function that returns either an item or a list of items, is there a single line statement that would initialize a new list from the results of calling the aforementioned function?</p>

<p><strong>Details:</strong> I've looked at the documents on python lists, and tried some things out on the repl, but I can't seem to figure this one out. </p>

<p>I'm calling a third party function that reads an xml document. The function sometimes returns a list and sometimes returns a single item (depending on how many xml entries exist). </p>

<p>For my purposes, I always need a list that I can iterate over - even if it is a length of one. The code below correctly accomplishes what I desire. Given Python's elegance, however, it seems clunky. I suspect there is a single-line way of doing it. </p>

<pre><code>def force_list(item_or_list):
    """
    Returns a list from either an item or a list.
    :param item_or_list: Either a single object, or a list of objects
    :return: A list of objects, potentially with a length of 1.
    """
    if item_or_list is None: return None
    _new_list = []
    if isinstance(item_or_list, list):
        _new_list.extend(item_or_list)
    else:
        _new_list.append(item_or_list)
    return _new_list
</code></pre>

<p>Thanks in advance, 
SteveJ</p>

<p>If you're looking for a one-liner about listifying the result of a function call:</p>

<p>Let's say there's a function called <code>func</code> that returns either an item or a list of items:</p>

<pre><code>elem = func()
answer = elem if isinstance(elem, list) else [elem]
</code></pre>

<p>That being said, you should really refactor <code>func</code> to return one type of thing - make it return a list of many elements, or in the case that it returns only one element, make it return a list with that element. Thus you can avoid such type-checking</p>

python list