Home > OS >  Update output inside a for loop when calculation completes
Update output inside a for loop when calculation completes

Time:02-24

I have a list of dates and am running a function for each of them like this:

dates = ['2017-12-29', '2018-12-31', '2019-12-31', '2020-12-31','2021-12-31']
for date in dates:
     display(key_metric(date))

This function renders a HTML table, and thus I get 5 outputs/tables one after the other like this:(this is just the first table)

enter image description here

Now, the key_metric function takes approximately 5-10 seconds to run for any argument. Now, what I want to achieve is that the tables should not append to one other but instead be updated at the same place. What I mean by this is: 1st table is displayed, when 2nd is calculated, 1st is removed and 2nd is displayed at the same place. Hope I'm clear.

I've tried IPython.display.clear_output but it clears the output instantly without waiting for other calculation to finish. Thanks!

CodePudding user response:

A simple solution of this would be to store the result of the function into a variable and then use it to display. For example:

dates = ['2017-12-29', '2018-12-31', '2019-12-31', '2020-12-31','2021-12-31']
for date in dates:
     key_met = key_metric(date)
     display.clear_output()
     display(key_met)

This will update the table when the calculation is completed.

  • Related