MGordon0405 MGordon0405 - 1 month ago 5
Python Question

Returning list inside of a list - Python

sorry this has undoubtably been asked but I can't seem to find it. I'm wanting to return a list from a list in python however when I try to do it, it seems to return the list as a string so will always access the first if statement.

def multpoly(entryList):

x = entryList.index(0)

if type(x) is list:
print("list")

if type(x) is str:
combined_str = ""

for x in entryList:
combined_str += x

return combined_str

print(multpoly(["1", "2", "3"]))

Answer
def multipoly(l): #l not list
    x = l[0]
    if isinstance(x, str):
        return ''.join(l)
    elif isinstance(x, list):
        return [a for sublist in l for a in sublist]
    else:
        raise ValueError("Not a list of strings or list of lists")

Use isinstance to check types. Don't use names that already have meanings, like list.

Comments