SteveJ SteveJ - 1 month ago 4x
Python Question

Python: Create list from function that returns single item or another list

(Python 3.5).

Problem Statement: 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?

Details: 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.

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).

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.

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):
return _new_list

Thanks in advance,


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

Let's say there's a function called func that returns either an item or a list of items:

elem = func()
answer = elem if not isinstance(elem, list) else [elem]

That being said, you should really refactor func 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