PYTHON 3 MEGA REFERENCE

Python
Cheat Sheet

A huge searchable, copy-ready Python 3 reference covering syntax, collections, functions, OOP, files, JSON, regex, typing, async, testing, SQLite, CLI tools, and more.

409 snippets
28 sections
1 standalone HTML file
Python note: This targets modern Python 3. Optional third-party tools such as Requests, Black, and Ruff must be installed separately.
print('Hello, world!')

Print output

name = 'Ada'

Assign a string

age = 18

Assign an integer

price = 19.99

Assign a float

active = True

Assign a boolean

value = None

Represent no value

x, y = 10, 20

Multiple assignment

x, y = y, x

Swap values

a = b = 0

Assign one value to multiple names

type(value)

Return an object's type

isinstance(value, int)

Check an object's type

id(value)

Return object identity

input('Name: ')

Read keyboard input

int('42')

Convert text to integer

float('3.14')

Convert text to float

str(123)

Convert a value to text

bool(value)

Convert a value to boolean

help(str)

Open built-in documentation

dir(object)

List available attributes

7 + 3

Addition

7 - 3

Subtraction

7 * 3

Multiplication

7 / 3

Floating-point division

7 // 3

Floor division

7 % 3

Remainder / modulo

7 ** 3

Exponentiation

abs(-8)

Absolute value

round(3.14159, 2)

Round to two decimal places

min(4, 2, 9)

Minimum

max(4, 2, 9)

Maximum

sum([1, 2, 3])

Sum values

divmod(17, 5)

Return quotient and remainder

pow(2, 8)

Raise to a power

x += 1

Increment

x -= 1

Decrement

x *= 2

Multiply and assign

x /= 2

Divide and assign

a == b

Equality comparison

a != b

Inequality comparison

a < b <= c

Chained comparison

a and b

Logical AND

a or b

Logical OR

not a

Logical NOT

text = 'hello'

Create a string

text = "hello"

Double-quoted string

text = '''multi
line'''

Multiline string

text[0]

First character

text[-1]

Last character

text[1:4]

Slice a string

text[::-1]

Reverse a string

len(text)

String length

text.upper()

Uppercase

text.lower()

Lowercase

text.title()

Title case

text.capitalize()

Capitalize first character

text.strip()

Trim outer whitespace

text.lstrip()

Trim left whitespace

text.rstrip()

Trim right whitespace

text.replace('old', 'new')

Replace text

text.split(',')

Split into a list

','.join(items)

Join strings

text.startswith('pre')

Test prefix

text.endswith('.txt')

Test suffix

'cat' in text

Check substring membership

text.find('cat')

Find substring index

text.count('a')

Count occurrences

f'Hello {name}'

Basic f-string

f'{price:.2f}'

Format decimal places

f'{value:>10}'

Right-align in a field

f'{number:,}'

Add thousands separators

repr(text)

Developer-facing representation

items = [1, 2, 3]

Create a list

items[0]

First item

items[-1]

Last item

items[1:4]

Slice a list

items.append(4)

Append one item

items.extend([4, 5])

Append multiple items

items.insert(1, 'x')

Insert at index

items.remove('x')

Remove first matching value

items.pop()

Remove and return last item

items.pop(0)

Remove and return by index

items.clear()

Remove all items

items.index('x')

Find index

items.count('x')

Count values

items.sort()

Sort in place

items.sort(reverse=True)

Sort descending

sorted(items)

Return a sorted copy

items.reverse()

Reverse in place

list(reversed(items))

Return a reversed list

items.copy()

Shallow-copy a list

len(items)

List length

'x' in items

Membership test

items + other

Concatenate lists

items * 3

Repeat a list

point = (10, 20)

Create a tuple

x, y = point

Unpack a tuple

single = (42,)

One-item tuple

colors = {'red', 'green'}

Create a set

set([1, 1, 2])

Remove duplicates

colors.add('blue')

Add to a set

colors.remove('red')

Remove or raise if missing

colors.discard('red')

Remove safely if present

a 

b|Set union

a & b

Set intersection

a - b

Set difference

a ^ b

Set symmetric difference

user = {'name': 'Ada', 'age': 18}

Create a dictionary

user['name']

Read a dictionary value

user.get('email')

Read safely

user.get('email', 'n/a')

Read with default

user.update({'age': 19})

Update multiple keys

user.pop('age')

Remove and return a key

user.keys()

Dictionary keys

user.values()

Dictionary values

user.items()

Key/value pairs

'name' in user

Check whether key exists

if x > 0:
    print('positive')

Basic if statement

if x > 0:
    print('positive')
else:
    print('other')

if / else

if x > 0:
    ...
elif x == 0:
    ...
else:
    ...

if / elif / else

status = 'adult' if age >= 18 else 'minor'

Conditional expression

if value is None:
    ...

Check for None

if not items:
    ...

Check for empty or falsy value

if 1 <= x <= 10:
    ...

Range check

for item in items:
    print(item)

Loop over items

for i in range(5):
    print(i)

Loop from 0 to 4

for i in range(2, 10, 2):
    print(i)

Loop with start stop step

for i, item in enumerate(items):
    print(i, item)

Loop with indexes

for a, b in zip(xs, ys):
    print(a, b)

Loop over two iterables

while condition:
    ...

While loop

break

Exit a loop

continue

Skip to next iteration

range(10)

Create a range

[x * 2 for x in items]

List comprehension

[x for x in items if x > 0]

Filtered list comprehension

{x * 2 for x in items}

Set comprehension

{k: v * 2 for k, v in data.items()}

Dictionary comprehension

(x * 2 for x in items)

Generator expression

[word.strip().lower() for word in lines if word.strip()]

Clean and filter text

[x for row in matrix for x in row]

Flatten one list level

def greet(name):
    return f'Hello {name}'

Define a function

def add(a, b=0):
    return a + b

Default argument

def func(*args):
    print(args)

Variable positional arguments

def func(**kwargs):
    print(kwargs)

Variable keyword arguments

def func(a, /, b, *, c):
    ...

Positional-only and keyword-only parameters

func(a=1, b=2)

Call with keyword arguments

values = [1, 2]
func(*values)

Unpack positional arguments

options = {'a': 1}
func(**options)

Unpack keyword arguments

lambda x: x * 2

Anonymous function

map(str.upper, words)

Map lazily

filter(str.isalpha, values)

Filter lazily

return value

Return a value

yield value

Yield from a generator

global name

Use a module-level name

nonlocal name

Use an enclosing-scope name

class User:
    pass

Define a class

class User:
    def __init__(self, name):
        self.name = name

Define an initializer

u = User('Ada')

Create an instance

u.name

Access an attribute

class User:
    def greet(self):
        return self.name

Define an instance method

@classmethod
def from_text(cls, text):
    return cls(text)

Define a class method

@staticmethod
def validate(value):
    return bool(value)

Define a static method

class Admin(User):
    pass

Subclass another class

super().__init__(name)

Call parent initializer

isinstance(obj, User)

Check instance type

issubclass(Admin, User)

Check inheritance

@property
def full_name(self):
    return self.name

Define a property

def __repr__(self):
    return f'User({self.name!r})'

Customize repr

def __str__(self):
    return self.name

Customize str

try:
    risky()
except ValueError:
    handle()

Catch a specific exception

try:
    ...
except (TypeError, ValueError) as e:
    print(e)

Catch multiple exception types

try:
    ...
except Exception as e:
    print(e)

Catch most normal exceptions

try:
    ...
else:
    success()

Run else when no exception occurs

try:
    ...
finally:
    cleanup()

Always run cleanup

raise ValueError('bad value')

Raise an exception

raise

Re-raise current exception

assert x > 0

Development-time assertion

class MyError(Exception):
    pass

Create a custom exception

from pathlib import Path

Import Path

p = Path('file.txt')

Create a Path object

p.exists()

Check whether path exists

p.is_file()

Check whether path is a file

p.is_dir()

Check whether path is a directory

p.name

Get file name

p.stem

Get filename without suffix

p.suffix

Get extension

p.parent

Get parent directory

p.resolve()

Resolve absolute path

p.read_text()

Read text

p.write_text('hello')

Write text

p.read_bytes()

Read bytes

p.write_bytes(data)

Write bytes

Path('newdir').mkdir(exist_ok=True)

Create directory

Path('a/b').mkdir(parents=True, exist_ok=True)

Create nested directories

list(Path('.').iterdir())

List directory contents

list(Path('.').glob('*.py'))

Glob files

list(Path('.').rglob('*.py'))

Recursive glob

with open('file.txt', 'r', encoding='utf-8') as f:
    text = f.read()

Read text with open

with open('file.txt', 'w', encoding='utf-8') as f:
    f.write('hello')

Write text with open

with open('file.txt', 'a', encoding='utf-8') as f:
    f.write('more')

Append text

import json

Import JSON tools

json.dumps(data)

Serialize to JSON string

json.dumps(data, indent=2)

Pretty JSON

json.loads(text)

Parse JSON string

json.dump(data, file_obj)

Write JSON to file

json.load(file_obj)

Read JSON from file

import csv

Import CSV tools

csv.reader(file_obj)

Read CSV rows

csv.writer(file_obj)

Write CSV rows

csv.DictReader(file_obj)

Read CSV as dictionaries

csv.DictWriter(file_obj, fieldnames=fields)

Write dictionary rows

from datetime import datetime, date, timedelta

Import date/time classes

datetime.now()

Current local date and time

date.today()

Today's date

datetime.now().isoformat()

ISO 8601 string

datetime.fromisoformat('2026-09-18T15:30:00')

Parse ISO datetime

datetime.strptime('09/18/2026', '%m/%d/%Y')

Parse formatted date

datetime.now().strftime('%Y-%m-%d')

Format date/time

datetime.now() + timedelta(days=7)

Add seven days

(end - start).total_seconds()

Elapsed seconds

import time
time.sleep(1)

Sleep one second

time.time()

Unix timestamp

time.perf_counter()

High-resolution timer

import re

Import regular expressions

re.search(r'\\d+', text)

Find first digit sequence

re.match(r'\\w+', text)

Match from string start

re.fullmatch(r'\\d{4}', text)

Require a full match

re.findall(r'\\b\\w+\\b', text)

Return all matches

re.sub(r'\\s+', ' ', text)

Replace repeated whitespace

re.split(r'[,;]', text)

Split using regex

pattern = re.compile(r'\\d+')

Compile a reusable pattern

m.group(0)

Read full match

m.groups()

Read captured groups

import math

Import math module

math.sqrt(81)

Square root

math.ceil(3.2)

Round upward

math.floor(3.8)

Round downward

math.pi

Pi constant

math.isclose(a, b)

Compare floats approximately

import statistics

Import statistics module

statistics.mean(values)

Mean

statistics.median(values)

Median

statistics.stdev(values)

Sample standard deviation

import random

Import pseudo-random tools

random.randint(1, 10)

Random integer

random.choice(items)

Choose one random item

random.sample(items, 3)

Choose unique random items

random.shuffle(items)

Shuffle a list in place

iter(items)

Get an iterator

next(iterator)

Get next item

next(iterator, default)

Get next or default

def countdown(n):
    while n:
        yield n
        n -= 1

Create generator function

(x * x for x in range(10))

Generator expression

yield from iterable

Yield from another iterable

enumerate(items, start=1)

Enumerate starting at 1

zip(a, b)

Pair iterables

reversed(items)

Reverse iterator

import os

Import a module

import math as m

Import with alias

from pathlib import Path

Import an object

if __name__ == '__main__':
    main()

Run only when executed directly

__name__

Current module name

__file__

Current module file path

python -m venv .venv

Create a virtual environment

source .venv/bin/activate

Activate venv on Linux/macOS

.venv\\Scripts\\activate

Activate venv in Windows Command Prompt

python -m pip install package

Install package

python -m pip install -U package

Upgrade package

python -m pip uninstall package

Uninstall package

python -m pip list

List installed packages

python -m pip freeze

Print installed versions

python -m pip freeze > requirements.txt

Save requirements

python -m pip install -r requirements.txt

Install requirements

python -m pip show package

Show package metadata

def add(a: int, b: int) -> int:
    return a + b

Function type hints

name: str = 'Ada'

Variable annotation

items: list[str] = []

List type hint

mapping: dict[str, int] = {}

Dictionary type hint

value: int 

None = None|Optional value

from typing import Any

Import Any

def func(value: Any) -> None:
    ...

Accept any type

from dataclasses import dataclass

Import dataclass

@dataclass
class User:
    name: str
    age: int = 0

Define a dataclass

from typing import TypedDict

Import TypedDict

class UserData(TypedDict):
    name: str
    age: int

Type a dictionary shape

import os

Import OS helpers

os.getcwd()

Get working directory

os.chdir('/tmp')

Change working directory

os.environ.get('HOME')

Read environment variable

os.environ['MODE'] = 'dev'

Set process environment variable

os.listdir('.')

List directory contents

os.stat('file.txt')

Get file metadata

import sys

Import interpreter helpers

sys.argv

Command-line arguments

sys.version

Python version string

sys.platform

Platform identifier

sys.exit(0)

Exit program

import subprocess

Import subprocess module

subprocess.run(['ls', '-lah'])

Run an external command

subprocess.run(['cmd'], check=True)

Raise if command fails

subprocess.run(['cmd'], capture_output=True, text=True)

Capture command output

result.stdout

Captured stdout

result.returncode

Exit status

from collections import Counter

Import Counter

Counter(words)

Count values

Counter(words).most_common(5)

Most common values

from collections import defaultdict

Import defaultdict

defaultdict(list)

Dictionary with automatic list defaults

from collections import deque

Import deque

deque(items)

Create double-ended queue

q.appendleft(value)

Append to left

q.popleft()

Pop from left

from functools import lru_cache

Import memoization helper

@lru_cache(maxsize=None)

Cache function results

from functools import partial

Import partial

partial(func, fixed_arg)

Pre-fill function arguments

import logging

Import logging

logging.basicConfig(level=logging.INFO)

Configure basic logging

logging.info('Started')

Info message

logging.warning('Something odd happened')

Warning message

logging.error('Failed')

Error message

logging.exception('Operation failed')

Log exception traceback

logger = logging.getLogger(__name__)

Create module logger

import argparse

Import argparse

parser = argparse.ArgumentParser()

Create parser

parser.add_argument('filename')

Add positional argument

parser.add_argument('-v', '--verbose', action='store_true')

Add boolean flag

parser.add_argument('--count', type=int, default=1)

Add typed optional argument

args = parser.parse_args()

Parse CLI arguments

args.filename

Access parsed argument

import asyncio

Import asyncio

async def main():
    ...

Define coroutine

await asyncio.sleep(1)

Non-blocking sleep

asyncio.run(main())

Run top-level coroutine

task = asyncio.create_task(coro())

Schedule coroutine

await task

Wait for task

await asyncio.gather(coro1(), coro2())

Run multiple awaitables concurrently

from threading import Thread

Import Thread

t = Thread(target=func, args=(value,))

Create a thread

t.start()

Start thread

t.join()

Wait for thread

from concurrent.futures import ThreadPoolExecutor

Import thread pool

with ThreadPoolExecutor() as ex:
    results = list(ex.map(func, items))

Map work across threads

from multiprocessing import Process

Import Process

p = Process(target=func)

Create child process

p.start(); p.join()

Start and wait for process

from concurrent.futures import ProcessPoolExecutor

Import process pool

import sqlite3

Import SQLite

conn = sqlite3.connect('app.db')

Open or create database

cur = conn.cursor()

Create cursor

cur.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')

Create table

cur.execute('INSERT INTO users(name) VALUES (?)', ('Ada',))

Insert with parameters

conn.commit()

Commit transaction

cur.execute('SELECT * FROM users')

Run SELECT

rows = cur.fetchall()

Fetch all rows

conn.close()

Close connection

with sqlite3.connect('app.db') as conn:
    conn.execute(...)

Use database context manager

import unittest

Import unittest

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(1 + 1, 2)

Define a unit test

python -m unittest

Discover and run unittest tests

self.assertTrue(value)

Assert truth

self.assertEqual(a, b)

Assert equality

self.assertRaises(ValueError)

Assert exception

python -m doctest file.py

Run doctests

python -m pip install requests

Install Requests

import requests

Import Requests

r = requests.get('https://example.com', timeout=10)

HTTP GET request

r.status_code

Read status code

r.text

Read response text

r.json()

Decode JSON response

requests.post(url, json=data, timeout=10)

POST JSON data

r.raise_for_status()

Raise on HTTP error

len(obj)

Number of items

sorted(iterable)

Return sorted list

reversed(sequence)

Reverse iterator

enumerate(iterable)

Pair with indexes

zip(a, b)

Pair multiple iterables

all(values)

True if all are truthy

any(values)

True if any are truthy

min(values)

Smallest value

max(values)

Largest value

sum(values)

Sum numeric values

set(iterable)

Create set

list(iterable)

Create list

tuple(iterable)

Create tuple

dict(pairs)

Create dictionary

numbers = [int(x) for x in input().split()]

Read space-separated integers

unique = list(dict.fromkeys(items))

Remove duplicates while preserving order

flat = [x for row in matrix for x in row]

Flatten one level

largest = max(items, key=len)

Find longest item

sorted_users = sorted(users, key=lambda u: u['name'])

Sort dictionaries by a field

pairs = dict(zip(keys, values))

Build dictionary from two sequences

text = ' '.join(text.split())

Normalize whitespace

next((x for x in items if predicate(x)), None)

Get first match or None

if value == None:

Prefer `is None` for None checks

from module import *

Avoid wildcard imports in normal application code

except:

Prefer catching specific exception types

a = [[0] * 3] * 3

Nested list multiplication shares inner lists

0.1 + 0.2 == 0.3

Floating-point values are approximate

items.sort()

sort() modifies a list and returns None

print(func())

A function that only prints usually returns None

def add(x, bucket=[]):
    bucket.append(x)
    return bucket

Avoid mutable default arguments; use None and create the list inside

python -m py_compile file.py

Compile one file and catch syntax errors

python -m compileall .

Compile a project and catch syntax errors

python -m pip install black

Install Black

python -m black file.py

Format with Black

python -m pip install ruff

Install Ruff

python -m ruff check .

Lint with Ruff

python -m ruff format .

Format with Ruff