Skip to content
Codeloom

Cheat Sheets

Python Cheat Sheet

Essential Python syntax, data structures, functions, comprehensions, file I/O, and common patterns in one quick-reference page.

9 sections 34 snippets

Variables and Types

Variable assignment
name = 'Alice'
age = 30
pi = 3.14
is_active = True
Type checking
type(name)       # <class 'str'>
isinstance(age, int)  # True
Type conversion
int('42')    # 42
str(3.14)    # '3.14'
float('2.5') # 2.5
list('abc')  # ['a', 'b', 'c']
Multiple assignment
a, b, c = 1, 2, 3
x = y = z = 0

Strings

f-strings
f'Hello, {name}! You are {age} years old.'
Common methods
s.upper()  s.lower()  s.strip()
s.split(',')  ','.join(lst)
s.replace('old', 'new')
s.startswith('He')  s.endswith('lo')
Slicing
s[0]      # first char
s[-1]     # last char
s[1:4]    # index 1 to 3
s[::-1]   # reverse
Multi-line strings
text = """Line one
Line two
Line three"""

Lists

Create and access
nums = [1, 2, 3, 4, 5]
nums[0]    # 1
nums[-1]   # 5
nums[1:3]  # [2, 3]
Modify
nums.append(6)
nums.insert(0, 0)
nums.extend([7, 8])
nums.pop()       # removes last
nums.remove(3)   # removes first 3
List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in nums if x % 2 == 0]
Sorting
nums.sort()              # in-place
sorted(nums, reverse=True) # new list

Dictionaries

Create and access
user = {'name': 'Alice', 'age': 30}
user['name']          # 'Alice'
user.get('email', '') # '' (default)
Modify
user['email'] = 'a@b.com'
user.update({'age': 31, 'city': 'NYC'})
del user['city']
user.pop('email')
Iterate
for key in user:
for key, val in user.items():
for val in user.values():
Dict comprehension
{k: v**2 for k, v in {'a': 1, 'b': 2}.items()}

Control Flow

if / elif / else
if x > 0:
    print('positive')
elif x == 0:
    print('zero')
else:
    print('negative')
for loop
for i in range(5):
    print(i)

for i, val in enumerate(lst):
    print(i, val)
while loop
while count > 0:
    count -= 1
Ternary expression
result = 'yes' if condition else 'no'

Functions

Define a function
def greet(name: str, loud: bool = False) -> str:
    msg = f'Hello, {name}!'
    return msg.upper() if loud else msg
*args and **kwargs
def func(*args, **kwargs):
    print(args)    # tuple of positional
    print(kwargs)  # dict of keyword
Lambda
double = lambda x: x * 2
sorted(users, key=lambda u: u['age'])
Decorators
def timer(fn):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = fn(*args, **kwargs)
        print(f'{time.time() - start:.2f}s')
        return result
    return wrapper

@timer
def slow(): ...

File I/O

Read a file
with open('data.txt', 'r') as f:
    content = f.read()
    # or line by line:
    lines = f.readlines()
Write a file
with open('out.txt', 'w') as f:
    f.write('Hello\n')
Read JSON
import json
with open('data.json') as f:
    data = json.load(f)
Write JSON
with open('out.json', 'w') as f:
    json.dump(data, f, indent=2)

Error Handling

try / except / finally
try:
    result = 10 / x
except ZeroDivisionError:
    result = 0
except (TypeError, ValueError) as e:
    print(e)
finally:
    cleanup()
Raise an exception
raise ValueError('x must be positive')

Common Patterns

Unpack with zip
names = ['a', 'b', 'c']
scores = [90, 80, 70]
for name, score in zip(names, scores):
    print(name, score)
any / all
any(x > 5 for x in nums)  # True if any match
all(x > 0 for x in nums)  # True if all match
collections.Counter
from collections import Counter
Counter('banana')  # Counter({'a': 3, 'n': 2, 'b': 1})
dataclasses
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float