Python Quick Reference
Data types, strings, lists, dicts, functions, classes, file I/O, error handling, comprehensions and virtual environments.
Data Types
# Numeric types
x = 42 # int
y = 3.14 # float
z = 2 + 3j # complex
big = 10 ** 100 # arbitrary precision integers
# Type checking
type(42) # <class 'int'>
isinstance(42, int) # True
isinstance(42, (int, float)) # True — check multiple types
# Type conversion
int('42') # 42
int(3.9) # 3 (truncates, doesn't round)
float('3.14') # 3.14
str(42) # '42'
bool(0) # False
bool('') # False
bool(None) # False
bool([]) # False
bool(1) # True
# None — Python's null equivalent
result = None
if result is None:
print('No result yet')
# Constants (convention: UPPER_CASE, not enforced)
MAX_RETRIES = 3
API_BASE_URL = 'https://api.example.com'
| Type | Mutable | Example |
|---|---|---|
int | No | 42, 0xff, 0b1010 |
float | No | 3.14, 1e-5 |
bool | No | True, False |
str | No | 'hello', "world" |
list | Yes | [1, 2, 3] |
tuple | No | (1, 2, 3) |
dict | Yes | {'key': 'value'} |
set | Yes | {1, 2, 3} |
frozenset | No | frozenset({1, 2}) |
NoneType | — | None |
String Operations
# String creation
single = 'hello'
double = "world"
multi = """This is
a multi-line string."""
raw = r'no \n escape' # raw string (useful for regex, paths)
# f-strings (Python 3.6+)
name = 'Alex'
age = 30
f'Hello, {name}! You are {age} years old.'
f'Result: {2 ** 10:,}' # 'Result: 1,024' — formatted
f'{name!r}' # "'Alex'" — repr
f'{3.14159:.2f}' # '3.14' — 2 decimal places
f'{42:08b}' # '00101010' — binary with padding
# Common methods
'hello world'.upper() # 'HELLO WORLD'
'HELLO'.lower() # 'hello'
'hello world'.title() # 'Hello World'
'hello world'.capitalize() # 'Hello world'
' hello '.strip() # 'hello'
' hello '.lstrip() # 'hello '
' hello '.rstrip() # ' hello'
# Search and replace
'hello world'.find('world') # 6 (-1 if not found)
'hello world'.index('world') # 6 (raises ValueError if not found)
'hello world'.count('l') # 3
'hello world'.startswith('hello') # True
'hello world'.endswith('world') # True
'hello world'.replace('world', 'Python') # 'hello Python'
# Split and join
'a,b,c'.split(',') # ['a', 'b', 'c']
'hello world'.split() # ['hello', 'world']
','.join(['a', 'b', 'c']) # 'a,b,c'
'\n'.join(lines)
# Checking content
'hello'.isalpha() # True
'123'.isdigit() # True
'hello123'.isalnum() # True
' '.isspace() # True
# Slicing
s = 'Hello, World!'
s[0] # 'H'
s[-1] # '!'
s[7:12] # 'World'
s[:5] # 'Hello'
s[7:] # 'World!'
s[::-1] # '!dlroW ,olleH' — reverse
Lists & Tuples
# Lists — ordered, mutable sequences
nums = [1, 2, 3, 4, 5]
mixed = [1, 'hello', True, 3.14]
nested = [[1, 2], [3, 4]]
empty = []
# Accessing elements
nums[0] # 1
nums[-1] # 5
nums[1:3] # [2, 3]
nums[::2] # [1, 3, 5] — every other element
# Modification
nums.append(6) # [1, 2, 3, 4, 5, 6]
nums.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6]
nums.extend([7, 8]) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
nums.remove(0) # remove first occurrence
popped = nums.pop() # remove and return last item
nums.pop(0) # remove and return item at index
nums.sort() # in-place sort (ascending)
nums.sort(reverse=True) # in-place sort (descending)
nums.reverse() # in-place reverse
nums.clear() # remove all items
# Non-mutating operations
sorted_nums = sorted(nums) # new sorted list
sorted_objs = sorted(users, key=lambda u: u['name'])
reversed_nums = list(reversed(nums)) # new reversed list
combined = nums + [6, 7] # concatenation
length = len(nums)
minimum = min(nums)
maximum = max(nums)
total = sum(nums)
# Searching
3 in nums # True — membership test
nums.index(3) # index of first occurrence (ValueError if missing)
nums.count(3) # number of occurrences
# Unpacking
first, *middle, last = [1, 2, 3, 4, 5]
# first=1, middle=[2, 3, 4], last=5
# Copy
shallow = nums.copy() # or nums[:] or list(nums)
import copy
deep = copy.deepcopy(nested) # deep copy for nested structures
# Tuples — ordered, immutable sequences
point = (10, 20)
single = (42,) # trailing comma for single-element tuple
x, y = point # unpacking
# Named tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
p.x # 10
p.y # 20
Dictionaries & Sets
# Dictionaries — key-value pairs
user = {
'name': 'Alex',
'email': '[email protected]',
'age': 30
}
# Access
user['name'] # 'Alex' (KeyError if missing)
user.get('name') # 'Alex'
user.get('role', 'user') # 'user' (default if missing)
# Modification
user['role'] = 'admin' # add or update
user.update({'age': 31, 'city': 'Berlin'})
del user['city'] # remove key
popped = user.pop('role') # remove and return value
user.setdefault('lang', 'en') # set only if key doesn't exist
# Iteration
for key in user: # iterate keys
print(key, user[key])
for key, value in user.items(): # iterate key-value pairs
print(f'{key}: {value}')
for value in user.values(): # iterate values only
print(value)
# Dict operations
user.keys() # dict_keys(['name', 'email', 'age'])
user.values() # dict_values(['Alex', '[email protected]', 30])
user.items() # dict_items([('name', 'Alex'), ...])
'name' in user # True — key membership test
len(user) # number of keys
# Merge (Python 3.9+)
defaults = {'theme': 'dark', 'lang': 'en'}
overrides = {'lang': 'de', 'debug': True}
merged = defaults | overrides # {'theme': 'dark', 'lang': 'de', 'debug': True}
defaults |= overrides # in-place merge
# Dict comprehension
squares = {n: n**2 for n in range(6)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# defaultdict
from collections import defaultdict
word_count = defaultdict(int)
for word in words:
word_count[word] += 1
# Counter
from collections import Counter
counter = Counter('abracadabra')
# Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
counter.most_common(3) # [('a', 5), ('b', 2), ('r', 2)]
# ─── Sets ──────────────────────────────────────────
# Sets — unordered, unique elements
colors = {'red', 'green', 'blue'}
empty_set = set() # not {} — that's an empty dict
# Modification
colors.add('yellow')
colors.discard('red') # no error if missing
colors.remove('green') # KeyError if missing
colors.pop() # remove arbitrary element
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # union: {1, 2, 3, 4, 5, 6}
a & b # intersection: {3, 4}
a - b # difference: {1, 2}
a ^ b # symmetric difference: {1, 2, 5, 6}
a <= b # subset check
a >= b # superset check
# Set comprehension
unique_lengths = {len(word) for word in words}
Functions
# Basic function
def greet(name):
return f'Hello, {name}!'
# Default arguments
def create_user(name, role='user', active=True):
return {'name': name, 'role': role, 'active': active}
# *args and **kwargs
def log(*args, **kwargs):
print('Args:', args)
print('Kwargs:', kwargs)
log(1, 2, 3, level='info', module='auth')
# Args: (1, 2, 3)
# Kwargs: {'level': 'info', 'module': 'auth'}
# Keyword-only arguments (after *)
def fetch(url, *, timeout=30, retries=3):
pass
fetch('https://api.example.com', timeout=10)
# Positional-only arguments (before /) — Python 3.8+
def pow(base, exp, /):
return base ** exp
# Lambda (anonymous function)
square = lambda x: x ** 2
add = lambda a, b: a + b
sorted_users = sorted(users, key=lambda u: u['name'])
# Type hints (Python 3.5+)
def add(a: int, b: int) -> int:
return a + b
def process(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
from typing import Optional, Union
def find_user(user_id: int) -> Optional[dict]:
...
# Decorators
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f'{func.__name__} took {elapsed:.4f}s')
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
# functools utilities
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
Classes & OOP
# Basic class
class User:
def __init__(self, name: str, email: str):
self.name = name
self.email = email
def greet(self) -> str:
return f'Hi, I am {self.name}'
def __repr__(self) -> str:
return f'User(name={self.name!r}, email={self.email!r})'
def __str__(self) -> str:
return self.name
user = User('Alex', '[email protected]')
# Class variables vs instance variables
class Config:
default_timeout = 30 # class variable — shared by all instances
def __init__(self, timeout=None):
self.timeout = timeout or Config.default_timeout # instance variable
# Properties
class Circle:
def __init__(self, radius: float):
self._radius = radius
@property
def radius(self) -> float:
return self._radius
@radius.setter
def radius(self, value: float):
if value < 0:
raise ValueError('Radius must be non-negative')
self._radius = value
@property
def area(self) -> float:
import math
return math.pi * self._radius ** 2
# Inheritance
class Animal:
def __init__(self, name: str):
self.name = name
def speak(self) -> str:
raise NotImplementedError
class Dog(Animal):
def speak(self) -> str:
return f'{self.name} says Woof!'
class Cat(Animal):
def speak(self) -> str:
return f'{self.name} says Meow!'
# Static and class methods
class MathUtils:
@staticmethod
def add(a, b):
return a + b
@classmethod
def from_string(cls, s: str):
return cls(*map(float, s.split(',')))
# Dataclasses (Python 3.7+)
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
tags: list[str] = field(default_factory=list)
in_stock: bool = True
@property
def display_price(self) -> str:
return f'${self.price:.2f}'
p = Product('Widget', 9.99, ['sale'])
# Generates __init__, __repr__, __eq__ automatically
# Abstract base classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float:
...
@abstractmethod
def perimeter(self) -> float:
...
File I/O
# Read file
with open('data.txt', 'r') as f:
content = f.read() # entire file as string
with open('data.txt', 'r') as f:
lines = f.readlines() # list of lines (with \n)
with open('data.txt', 'r') as f:
for line in f: # iterate line by line (memory efficient)
print(line.strip())
# Write file
with open('output.txt', 'w') as f:
f.write('Hello, World!\n')
f.write('Second line\n')
# Append to file
with open('log.txt', 'a') as f:
f.write(f'{datetime.now()} — Event occurred\n')
# Write multiple lines
with open('output.txt', 'w') as f:
f.writelines(['Line 1\n', 'Line 2\n', 'Line 3\n'])
# Binary mode
with open('image.png', 'rb') as f:
data = f.read()
with open('copy.png', 'wb') as f:
f.write(data)
# JSON
import json
with open('config.json', 'r') as f:
config = json.load(f) # parse file to dict
with open('output.json', 'w') as f:
json.dump(data, f, indent=2) # write dict to file
json_str = json.dumps(data) # dict to JSON string
parsed = json.loads(json_str) # JSON string to dict
# CSV
import csv
with open('data.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
print(row['name'], row['email'])
with open('output.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['name', 'email'])
writer.writeheader()
writer.writerow({'name': 'Alex', 'email': '[email protected]'})
# pathlib (modern path handling)
from pathlib import Path
p = Path('src') / 'utils' / 'helpers.py'
p.exists() # True/False
p.is_file() # True/False
p.is_dir() # True/False
p.read_text() # read file content
p.write_text('hello') # write file content
p.name # 'helpers.py'
p.stem # 'helpers'
p.suffix # '.py'
p.parent # Path('src/utils')
Path('logs').mkdir(parents=True, exist_ok=True)
list(Path('src').glob('**/*.py')) # recursive file search
Error Handling
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero')
# Multiple exception types
try:
value = int(input('Enter a number: '))
result = 100 / value
except ValueError:
print('Not a valid number')
except ZeroDivisionError:
print('Cannot divide by zero')
except (TypeError, KeyError) as e:
print(f'Error: {e}')
# Catch all exceptions (use sparingly)
try:
risky_operation()
except Exception as e:
print(f'Unexpected error: {e}')
# else — runs if no exception occurred
try:
data = fetch_data()
except ConnectionError:
data = cached_data()
else:
process(data)
# finally — always runs
try:
f = open('data.txt')
data = f.read()
except FileNotFoundError:
data = ''
finally:
f.close() # always close, even if exception occurred
# Raise exceptions
def validate_age(age):
if not isinstance(age, int):
raise TypeError('Age must be an integer')
if age < 0 or age > 150:
raise ValueError(f'Invalid age: {age}')
return age
# Custom exceptions
class AppError(Exception):
def __init__(self, message, code=None):
super().__init__(message)
self.code = code
class NotFoundError(AppError):
def __init__(self, resource='Resource'):
super().__init__(f'{resource} not found', code=404)
class ValidationError(AppError):
def __init__(self, field, message):
super().__init__(f'{field}: {message}', code=422)
self.field = field
# Exception chaining
try:
data = json.loads(raw)
except json.JSONDecodeError as e:
raise ValidationError('body', 'Invalid JSON') from e
# Context managers for resource management
from contextlib import contextmanager
@contextmanager
def database_connection(url):
conn = connect(url)
try:
yield conn
finally:
conn.close()
with database_connection('postgres://...') as conn:
conn.execute('SELECT 1')
List Comprehensions & Generators
# List comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# With transformation and condition
names = [user['name'].upper() for user in users if user['active']]
# Nested comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [n for row in matrix for n in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Dict comprehension
name_lengths = {name: len(name) for name in names}
inverted = {v: k for k, v in original.items()}
# Set comprehension
unique_words = {word.lower() for word in text.split()}
# Generator expression (lazy — memory efficient)
total = sum(x**2 for x in range(1_000_000))
# Generator function
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
first_10 = [next(fib) for _ in range(10)]
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# Generator with send
def accumulator():
total = 0
while True:
value = yield total
total += value
acc = accumulator()
next(acc) # initialize: 0
acc.send(10) # 10
acc.send(20) # 30
acc.send(5) # 35
# itertools — powerful iteration tools
from itertools import chain, islice, groupby, product, combinations
list(chain([1, 2], [3, 4], [5])) # [1, 2, 3, 4, 5]
list(islice(fibonacci(), 8)) # first 8 Fibonacci numbers
list(combinations('ABCD', 2)) # [('A','B'), ('A','C'), ...]
list(product([0, 1], repeat=3)) # all 3-bit binary combos
# Walrus operator (Python 3.8+) — assignment in expressions
results = [y for x in data if (y := process(x)) is not None]
Virtual Environments & pip
# Create a virtual environment
python -m venv .venv
# Activate
source .venv/bin/activate # Linux/macOS
# .venv\Scripts\activate # Windows
# Deactivate
deactivate
# pip — package management
pip install requests # install package
pip install requests==2.31.0 # specific version
pip install 'requests>=2.28,<3' # version range
pip install -e . # install current project (editable)
pip install -r requirements.txt # install from file
pip uninstall requests
# requirements.txt
pip freeze > requirements.txt # export installed packages
# Example requirements.txt:
# requests==2.31.0
# flask>=3.0,<4.0
# sqlalchemy~=2.0
# python-dotenv
# pip commands
pip list # list installed packages
pip show requests # package details
pip install --upgrade requests # update a package
pip check # verify dependencies
# pyproject.toml (modern project config)
# [project]
# name = "myproject"
# version = "1.0.0"
# requires-python = ">=3.11"
# dependencies = [
# "requests>=2.28",
# "flask>=3.0",
# ]
#
# [project.optional-dependencies]
# dev = ["pytest", "ruff", "mypy"]
# Install with optional dependencies
pip install -e '.[dev]'
# uv — fast Python package installer (Rust-based alternative to pip)
# pip install uv
uv pip install requests
uv pip sync requirements.txt
uv venv # create venv
uv pip compile requirements.in -o requirements.txt # lock deps
Always use virtual environments for projects to avoid dependency conflicts. For reproducible builds, pin exact versions in
requirements.txt using pip freeze or a lock file tool like pip-compile or uv.