0

I have a function

async def hello(a):
    await asyncio.sleep(2)
    print(a)

I want to call this function for several elements in a list asynchronously

list =  ['words','I','need','to','print','parallely']

Something like this, but the below code runs one after the other.

for word in list:
    await hello(word)

Is there a better way to do this? I had used asyncio.create_task but not sure how to use them in loops.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rakesh SK
  • 47
  • 1
  • 3

1 Answers1

4

This is an example of how it should work:

import asyncio

list_1 = 'hi i am cool'.split()

async def hello(a):
    await asyncio.sleep(2)
    print(a)
    
async def run_tasks():
   tasks = [hello(word) for word in list_1]
   await asyncio.wait(tasks)

def main():
   loop = asyncio.new_event_loop()
   asyncio.set_event_loop(loop)
   loop.run_until_complete(run_tasks())
   loop.close()

main()

Sample output:

am
i
cool
hi

The above code is mainly for demonstration but the new and easier way to do so is:

def main2():
    asyncio.run(run_tasks())

main2()

Sample output:

i
hi
cool
am

Note:

As suggested in the comments, to preserve the order of inputs, define run_tasks as:

async def run_tasks():
   tasks = [hello(word) for word in list_1]
   await asyncio.gather(*tasks)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
adir abargil
  • 5,495
  • 3
  • 19
  • 29