print('Hello, world!')Print output
A huge searchable, copy-ready Python 3 reference covering syntax, collections, functions, OOP, files, JSON, regex, typing, async, testing, SQLite, CLI tools, and more.
print('Hello, world!')Print output
name = 'Ada'Assign a string
age = 18Assign an integer
price = 19.99Assign a float
active = TrueAssign a boolean
value = NoneRepresent no value
x, y = 10, 20Multiple assignment
x, y = y, xSwap values
a = b = 0Assign 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 + 3Addition
7 - 3Subtraction
7 * 3Multiplication
7 / 3Floating-point division
7 // 3Floor division
7 % 3Remainder / modulo
7 ** 3Exponentiation
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 += 1Increment
x -= 1Decrement
x *= 2Multiply and assign
x /= 2Divide and assign
a == bEquality comparison
a != bInequality comparison
a < b <= cChained comparison
a and bLogical AND
a or bLogical OR
not aLogical 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 textCheck 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 itemsMembership test
items + otherConcatenate lists
items * 3Repeat a list
point = (10, 20)Create a tuple
x, y = pointUnpack 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 & bSet intersection
a - bSet difference
a ^ bSet 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['email'] = '[email protected]'Add or update key
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 userCheck 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
breakExit a loop
continueSkip 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 + bDefault 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 * 2Anonymous function
map(str.upper, words)Map lazily
filter(str.isalpha, values)Filter lazily
return valueReturn a value
yield valueYield from a generator
global nameUse a module-level name
nonlocal nameUse an enclosing-scope name
class User:
passDefine a class
class User:
def __init__(self, name):
self.name = nameDefine an initializer
u = User('Ada')Create an instance
u.nameAccess an attribute
class User:
def greet(self):
return self.nameDefine 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):
passSubclass 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.nameDefine a property
def __repr__(self):
return f'User({self.name!r})'Customize repr
def __str__(self):
return self.nameCustomize 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
raiseRe-raise current exception
assert x > 0Development-time assertion
class MyError(Exception):
passCreate a custom exception
from pathlib import PathImport 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.nameGet file name
p.stemGet filename without suffix
p.suffixGet extension
p.parentGet 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 jsonImport 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 csvImport 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, timedeltaImport 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 reImport 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 mathImport math module
math.sqrt(81)Square root
math.ceil(3.2)Round upward
math.floor(3.8)Round downward
math.piPi constant
math.isclose(a, b)Compare floats approximately
import statisticsImport statistics module
statistics.mean(values)Mean
statistics.median(values)Median
statistics.stdev(values)Sample standard deviation
import randomImport 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 -= 1Create generator function
(x * x for x in range(10))Generator expression
yield from iterableYield from another iterable
enumerate(items, start=1)Enumerate starting at 1
zip(a, b)Pair iterables
reversed(items)Reverse iterator
import osImport a module
import math as mImport with alias
from pathlib import PathImport an object
if __name__ == '__main__':
main()Run only when executed directly
__name__Current module name
__file__Current module file path
python -m venv .venvCreate a virtual environment
source .venv/bin/activateActivate venv on Linux/macOS
.venv\\Scripts\\activateActivate venv in Windows Command Prompt
python -m pip install packageInstall package
python -m pip install -U packageUpgrade package
python -m pip uninstall packageUninstall package
python -m pip listList installed packages
python -m pip freezePrint installed versions
python -m pip freeze > requirements.txtSave requirements
python -m pip install -r requirements.txtInstall requirements
python -m pip show packageShow package metadata
def add(a: int, b: int) -> int:
return a + bFunction 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 AnyImport Any
def func(value: Any) -> None:
...Accept any type
from dataclasses import dataclassImport dataclass
@dataclass
class User:
name: str
age: int = 0Define a dataclass
from typing import TypedDictImport TypedDict
class UserData(TypedDict):
name: str
age: intType a dictionary shape
import osImport 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 sysImport interpreter helpers
sys.argvCommand-line arguments
sys.versionPython version string
sys.platformPlatform identifier
sys.exit(0)Exit program
import subprocessImport 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.stdoutCaptured stdout
result.returncodeExit status
from collections import CounterImport Counter
Counter(words)Count values
Counter(words).most_common(5)Most common values
from collections import defaultdictImport defaultdict
defaultdict(list)Dictionary with automatic list defaults
from collections import dequeImport deque
deque(items)Create double-ended queue
q.appendleft(value)Append to left
q.popleft()Pop from left
from functools import lru_cacheImport memoization helper
@lru_cache(maxsize=None)Cache function results
from functools import partialImport partial
partial(func, fixed_arg)Pre-fill function arguments
import loggingImport 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 argparseImport 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.filenameAccess parsed argument
import asyncioImport 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 taskWait for task
await asyncio.gather(coro1(), coro2())Run multiple awaitables concurrently
from threading import ThreadImport Thread
t = Thread(target=func, args=(value,))Create a thread
t.start()Start thread
t.join()Wait for thread
from concurrent.futures import ThreadPoolExecutorImport thread pool
with ThreadPoolExecutor() as ex:
results = list(ex.map(func, items))Map work across threads
from multiprocessing import ProcessImport Process
p = Process(target=func)Create child process
p.start(); p.join()Start and wait for process
from concurrent.futures import ProcessPoolExecutorImport process pool
import sqlite3Import 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 unittestImport unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)Define a unit test
python -m unittestDiscover and run unittest tests
self.assertTrue(value)Assert truth
self.assertEqual(a, b)Assert equality
self.assertRaises(ValueError)Assert exception
python -m doctest file.pyRun doctests
python -m pip install requestsInstall Requests
import requestsImport Requests
r = requests.get('https://example.com', timeout=10)HTTP GET request
r.status_codeRead status code
r.textRead 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] * 3Nested list multiplication shares inner lists
0.1 + 0.2 == 0.3Floating-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 bucketAvoid mutable default arguments; use None and create the list inside
python -m py_compile file.pyCompile one file and catch syntax errors
python -m compileall .Compile a project and catch syntax errors
python -m pip install blackInstall Black
python -m black file.pyFormat with Black
python -m pip install ruffInstall Ruff
python -m ruff check .Lint with Ruff
python -m ruff format .Format with Ruff