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>Another way of doing this in a single line is</p>

<pre><code>def force_list(item_or_list=[]):
    return item_or_list if type(item_or_list) is list else [item_or_list]
</code></pre>

<p>print force_list("test")</p>

<blockquote>
  <p>test</p>
</blockquote>

<p>print force_list(["test","test2"])</p>

<blockquote>
  <p>["test","test2"]</p>
</blockquote>

python list