I have a question that I haven't quite found a good solution to. I'm looking for a better way to append function output to two or more lists, without using temp variables. Example below:
def f():
return 5,6
a,b = [], []
for i in range(10):
tmp_a, tmp_b = f()
a.append(tmp_a)
b.append(temp_b)
I've tried playing around with something like zip(*f()), but haven't quite found a solution that way. Any way to remove those temp vars would be super helpful though, thanks!
Edit for additional info: In this situation, the number of outputs from the function will always equal the number of lists that are being appended to. The main reason I'm looking to get rid of temps is for the case where there are maybe 8-10 function outputs, and having that many temp variables would get messy (though I don't really even like having two).
First solution: we make a list of all results, then transpose it
Or, all in one line:
A different solution, building the lists at each iteration, so that you can use them while they're being built:
Note about
list(map(...))
: in Python3,map
returns a generator, so we must use it if we want the lambda to be executed.list
does it.I'd do
Not sure how pythonic it is for you though.
For your specific case, the
zip
answers are great.Using
itertools.cycle
anditertools.chain
is a different approach from the existing answers that might come in handy if you have a lot of pre-existing lists that you want to append to in a round-robin fashion. It also works when your function returns more values than you have lists.