Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One liner for extend loop python

Tags:

python

I have the following code lines:

records = []

for future in futures:
  records.extends(future.result())

each future returns a list.

How can I write the above code but in one liner?

records = [future.result() for future in futures]

would result in a list inside list.

I have millions of records, i would rather not flat it after creating lists inside list

like image 428
Dejell Avatar asked Dec 13 '22 22:12

Dejell


2 Answers

records = [r for future in futures for r in future.result()]
like image 184
Błotosmętek Avatar answered Dec 16 '22 10:12

Błotosmętek


There are many ways to do this:

  1. Use itertools.chain:
    records = list(itertools.chain.from_iterable(future.result() for future in futures))
  2. Use the itertools consume recipe:
    records = collections.deque((records.extend(future.result()) for future in futures), maxlen=0)
  3. Use a throw-away list:
    [records.extend(future.result()) for future in futures]. records will now have all the required content, and you will have temporarily made a list of Nones

You could also do functools.reduce(operator.add, (future.result() for future in futures)), but that wouldn't scale very well

like image 23
inspectorG4dget Avatar answered Dec 16 '22 11:12

inspectorG4dget