Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python function yields tuple and only one element is wanted

I have a function

def f():
    # whatever
    yield (a,b)

Now I would like to collect all the a but not b. Also I want the result aa to be a list instead of iterator. Right now I use

aa, _ = zip(*f())

Is this the best one can do in terms of space/time efficiency?

like image 258
nos Avatar asked Dec 08 '16 22:12

nos


1 Answers

zip(*seq) has to ingest the whole generator, before it can output the columns. This is not efficient.

Just stick to a list comprehension. You could use tuple assignment:

aa = [a for a, _ in f()]

or use indexing:

aa = [tup[0] for tup in f()]

If you don't have to have all values available for random access or other operations that must have a list, you can use a generator expression to maintain the memory efficiency:

aa = (a for a, _ in f())
like image 186
Martijn Pieters Avatar answered Nov 15 '22 12:11

Martijn Pieters