siamii
siamii

Reputation: 24124

How to read variable number of outputs

I'm running python 2.7.3. I have a list of functions that I invoke each. Some functions return more than one outputs. I'd like to save all the outputs of all functions in a list. How can I do that?

def f1():
    return [1,2], [3,4]
def f2():
    return [5,6]
my_outputs = []
my_funcs = [f1, f2]
for func in my_funcs:
    output_list* = func() # does this work?
    # a,b,c... = func()
    my_outputs.extend(output_list)

print my_outputs
[[1,2], [3,4], [5,6]]

Upvotes: 0

Views: 85

Answers (2)

msvalkon
msvalkon

Reputation: 12077

You can check the return type with isinstance, although it's not very pythonic.

 my_outputs = []
 my_funcs = [f1, f2, f3]
 for func in my_funcs:
    result = func()
    if isinstance(result, tuple):
        my_outputs.extend(result)
    else:
        my_outputs.append(result)

Upvotes: 1

Nicolas Barbey
Nicolas Barbey

Reputation: 6797

sum((list(f()) for f in [f1, f2]), [])

Upvotes: 1

Related Questions