Skip to content
Python

asyncio Asynchronous Programming

Implement asynchronous concurrency with asyncio.

By EZ4Code Team
asyncioasync

Code

import asyncio

async def fetch(url):
    await asyncio.sleep(1)
    return f"Data from {url}"

async def main():
    # Concurrent execution
    results = await asyncio.gather(
        fetch("url1"),
        fetch("url2"),
        fetch("url3")
    )
    print(results)

asyncio.run(main())

# Async iteration
async def counter():
    for i in range(3):
        await asyncio.sleep(0.5)
        yield i

Explanation

asyncio is suitable for IO-intensive tasks; gather runs multiple coroutines concurrently.

More Python Snippets