Python Cheatsheet

Quick reference for Python basics — structures, functions, loops, and concurrency.

Data Structures

Structure Syntax Notes
List [1, 2, 3] Ordered, mutable
Tuple (1, 2, 3) Ordered, immutable
Dict {"a": 1} Key-value
Set {1, 2, 3} Unique values
deque deque([1,2]) Double-ended queue; collections

Functions

# Function definition
def greet(name: str) -> str:
    return f"Hello, {name}"

# Default / keyword args
def connect(host="localhost", port=3000):
    return f"{host}:{port}"

# *args / **kwargs
def log(*args, **kwargs):
    print(args, kwargs)

# Lambda
square = lambda x: x ** 2

Loops & Iteration

# for
for n in [1, 2, 3]:
    print(n)

# enumerate
for i, val in enumerate(["a", "b"]):
    print(i, val)

# list comprehension
doubled = [n * 2 for n in range(5)]

# dict comprehension
squares = {n: n**2 for n in range(5)}

# while
i = 0
while i < 5:
    print(i)
    i += 1

Threading & Concurrency

import threading
from queue import Queue

# Threads
def worker(name):
    print(f"Worker {name}")

threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)]
for t in threads:
    t.start()
for t in threads:
    t.join()

# Queue (thread-safe)
q = Queue()
q.put("job")
item = q.get()

# concurrent.futures
from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=4) as executor:
    results = list(executor.map(lambda x: x**2, range(10)))

# asyncio
import asyncio

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

async def main():
    results = await asyncio.gather(
        fetch("a"), fetch("b")
    )

asyncio.run(main())