Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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):
        _new_list.extend(item_or_list)
    else:
        _new_list.append(item_or_list)
    return _new_list

Thanks in advance, SteveJ

like image 295
SteveJ Avatar asked Mar 12 '23 04:03

SteveJ


2 Answers

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

like image 95
inspectorG4dget Avatar answered Mar 13 '23 17:03

inspectorG4dget


You may check it like in one line as:

 if item: # Check whether it is not None or empty list
     # Check if it is list. If not, append it to existing list after converting it to list
     _new_list.extend(item if isiinstance(item, list) else [item])
like image 23
Moinuddin Quadri Avatar answered Mar 13 '23 19:03

Moinuddin Quadri