(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
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
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])
Another way of doing this in a single line is
def force_list(item_or_list=[]):
return item_or_list if type(item_or_list) is list else [item_or_list]
print force_list("test")
test
print force_list(["test","test2"])
["test","test2"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.