Python: Using async/await with loops (for & while loops)

Updated: July 10, 2023 By: Khue Post a comment

This concise, practical article will walk you through some examples that showcase different scenarios for using the async and await keywords with for loops and while loops in Python, from basic asynchronous loops to parallel execution, rate limiting, and external termination conditions.

Basic Example: Asynchronous Loop

In this basic example, we define an async function countdown() that prints numbers from 1 to 10 asynchronously using await and asyncio.sleep(). We use a for loop to iterate through the numbers and await the sleep operation to introduce a delay of one second between each number.

import asyncio

async def countdown():
    for i in range(1, 11):
        print(i)
        await asyncio.sleep(1)

async def main():
    await countdown()

asyncio.run(main())

Parallel Execution with Gather

This example demonstrates running multiple coroutines concurrently using asyncio.gather() and an async loop. We’ll define a coroutine countdown() (it isn’t the same as the one in the preceding example) that prints numbers with a delay. Inside the main() function, we create tasks for each coroutine using asyncio.create_task() and use asyncio.gather() to wait for all tasks to complete.

import asyncio

async def countdown(n):
    for i in range(1, n + 1):
        print(i)
        await asyncio.sleep(1)

async def main():
    tasks = [
        asyncio.create_task(countdown(10)),
        asyncio.create_task(countdown(7)),
    ]
    await asyncio.gather(*tasks)

asyncio.run(main())

Looping with Rate Limiting

This example showcases an async loop with rate limiting using asyncio.sleep() to control the frequency of execution. We define a coroutine process_item() that processes each item with a delay. Inside the main() function, we iterate over a list of items and await the execution of process_item() with a sleep interval between each iteration.

import asyncio

async def process_item(item):
    print(f"Processing item: {item}")
    await asyncio.sleep(1)

async def main():
    items = [1, 2, 3, 4, 5]
    for item in items:
        await process_item(item)

        # Rate limit between iterations
        await asyncio.sleep(0.5)  

asyncio.run(main())

Looping with External Termination Condition

This example demonstrates an async loop with an external termination condition. We define a coroutine countdown() that prints numbers with a delay. Inside the main() function, we use a while loop with an external condition (count) to determine when to stop the loop.

import asyncio

async def countdown():
    count = 5
    while count > 0:
        print(count)
        await asyncio.sleep(1)
        count -= 1

async def main():
    await countdown()

asyncio.run(main())

Conclusion

The examples in this article demonstrate how async/await can be used effectively with loops to handle various situations in asynchronous programming. If you have any questions related to this topic, please comment. Happy coding & have a nice day!