'how to converting a for loop with await into asyncio.gather()

how do I write the following piece of code using asyncio.gather and map?

        for i in range(len(data)):
            candlestick = data[i]
            candlesticks = data[0: i + 1]
            await strategy.execute(candlesticks, candlestick.startTime)


Solution 1:[1]

You could do it like this:

from asyncio import gather, create_task
tasks = []
for i in range(len(data)):
    candlestick = data[i]
    candlesticks = data[0: i + 1]
    tasks.append(create_task(strategy.execute(candlesticks, candlestick.startTime)))
results = await gather(*tasks, return_exceptions=False)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user56700