Multiple return from function call in list comprehension

Viewed 480

I need an explanation about the functioning of Python related to this specific case: I have a list comprehension that calls a function for every element of the listA. With this code:

listA = [1,1,1]

def operation(n):
    result = []
    *code do something*
    result = [a,b,c]
    return result 

listB = [operation(element) for element in listA]

I obtain:

listB = [[a,b,c],[a,b,c],[a,b,c]]

How can I return multiple element of a list individually so as to achieve this?

listB = [a,b,c,a,b,c,a,b,c]

What I tried is:

ListA = [1,1,1]

def operation(n):
    result = []
    *code do something*
    result = [a,b,c]
    for x in result:
        return x

Output: [a,a,a] instead of [a,b,c,a,b,c,a,b,c]

Note1: cannot use any import

Note2: I put a simplistic case and I cannot transform the list in flat list, what I would need is to be able to return multiple values ​​from a single call, is it possible? Thank you

5 Answers

You can iterate on the items of each returned list to flatten the output:

listB = [item for element in listA for item in operation(element)]

Note that the order of the for expressions is the same as the one you would have if you wrote 'normal' loops.

Try this:

listA = [1, 1, 1]

def operation(n):
    result = [i for i in ["a", "b", "c"] * len(listA) for x in i]
    return result

listB = operation(listA)
print(listB)

we provide a flatten list when we make a nested for-loop.

The following should work (for this specific structure of your list, not recommended for some other structures):

listB = sum([operation(element) for element in listA], [])

You could use your function as a generator with a secondary loop through the elements and then iterate over the generator to get your list.

listA = [1,1,1]

def operation(n):
    result = []
    ...
    result = ['a','b','c']
    
    ############
    for i in result:
        yield i      #change this to yield
    ############
    
[j for i in listA for j in operation(i)]
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

if you just want to achieve your final output one way of doing it can be by using extend function like this

for i in listA:
    listB.extend(operation(listA))

this will also generate the same result but it's not a list comprehension

Related