← All Tools

🐍 Python Cheat Sheet

Quick reference for Python developers — 100+ snippets

Showing all commands

Basics & Variables

x = 10
Variable assignment
x, y, z = 1, 2, 3
Multiple assignment
type(x)
Check type of variable
isinstance(x, int)
Check if instance of type
int("42")
Convert string to integer
str(42)
Convert to string
float("3.14")
Convert to float
bool(0) # False
Convert to boolean
input("Enter: ")
Read user input
print(f"Hello {name}")
F-string formatting

Strings

s.upper()
Convert to uppercase
s.lower()
Convert to lowercase
s.strip()
Remove leading/trailing whitespace
s.split(",")
Split string into list
",".join(lst)
Join list into string
s.replace("old", "new")
Replace substring
s.find("sub")
Find index of substring (-1 if not found)
s.startswith("pre")
Check if starts with prefix
s.endswith(".py")
Check if ends with suffix
s[1:5]
Slice string (index 1 to 4)
s[::-1]
Reverse string
len(s)
Get string length
s.isdigit()
Check if all characters are digits
s.title()
Title Case Each Word

Lists

lst = [1, 2, 3]
Create a list
lst.append(4)
Add item to end
lst.insert(0, "first")
Insert at index
lst.remove(2)
Remove first occurrence of value
lst.pop()
Remove and return last item
lst.pop(0)
Remove and return item at index
lst.sort()
Sort list in place
sorted(lst)
Return new sorted list
lst.reverse()
Reverse list in place
lst.index(2)
Find index of value
lst.count(2)
Count occurrences
lst.extend([4, 5])
Add multiple items
[x**2 for x in range(10)]
List comprehension
[x for x in lst if x > 2]
Filtered list comprehension
lst[::2]
Every other element

Dictionaries

d = {"key": "value"}
Create a dictionary
d["key"]
Access value by key
d.get("key", "default")
Get with default value
d["new_key"] = "val"
Add or update key
del d["key"]
Delete a key
d.keys()
Get all keys
d.values()
Get all values
d.items()
Get key-value pairs
d.update({"a": 1})
Merge dictionaries
d.pop("key")
Remove key and return value
"key" in d
Check if key exists
{k: v for k, v in d.items()}
Dict comprehension
d | {"new": 1}
Merge operator (Python 3.9+)

Sets & Tuples

s = {1, 2, 3}
Create a set
s.add(4)
Add element to set
s.discard(2)
Remove element (no error if missing)
s1 | s2
Union of two sets
s1 & s2
Intersection of two sets
s1 - s2
Difference (in s1 but not s2)
t = (1, 2, 3)
Create a tuple (immutable)
a, b, c = t
Unpack tuple
a, *rest = (1,2,3,4)
Extended unpacking

Control Flow

if x > 0: ... elif x == 0: ... else: ...
If/elif/else
for item in iterable:
For loop
for i, val in enumerate(lst):
Loop with index
for k, v in d.items():
Loop over dict
while condition:
While loop
break
Exit loop
continue
Skip to next iteration
x if condition else y
Ternary operator
match value: case 1: ... case _: ...
Match statement (Python 3.10+)

Functions

def func(a, b=10):
Function with default argument
def func(*args, **kwargs):
Variable arguments
lambda x: x * 2
Lambda (anonymous) function
def func() -> int:
Type hint for return value
def func(x: str, y: int = 0):
Type hints for parameters
map(func, iterable)
Apply function to each element
filter(func, iterable)
Filter elements by function
from functools import reduce
Import reduce for accumulation
@decorator
Apply decorator to function

Classes & OOP

class Dog: def __init__(self, name): self.name = name
Basic class with constructor
class Puppy(Dog):
Inheritance
super().__init__()
Call parent constructor
@property
Getter property
@staticmethod
Static method (no self)
@classmethod
Class method (cls instead of self)
def __str__(self):
String representation
def __len__(self):
Support len()
from dataclasses import dataclass @dataclass class Point: x: float y: float
Dataclass (auto __init__, __repr__)

File I/O

with open("f.txt") as f: text = f.read()
Read entire file
with open("f.txt") as f: lines = f.readlines()
Read file as list of lines
with open("f.txt", "w") as f: f.write("text")
Write to file
with open("f.txt", "a") as f: f.write("more")
Append to file
import json with open("d.json") as f: data = json.load(f)
Read JSON file
json.dumps(data, indent=2)
Convert to JSON string
import csv with open("d.csv") as f: reader = csv.reader(f)
Read CSV file
from pathlib import Path p = Path("dir/file.txt")
Modern path handling
Path("dir").mkdir(exist_ok=True)
Create directory
list(Path(".").glob("*.py"))
Find files by pattern

Error Handling

try: risky() except ValueError as e: print(e)
Try/except with specific error
except (TypeError, KeyError):
Catch multiple exceptions
finally:
Always runs after try/except
raise ValueError("msg")
Raise an exception
assert x > 0, "x must be positive"
Assert condition
class MyError(Exception): pass
Custom exception class

Modules & Imports

import os
Import module
from os import path
Import specific item
import numpy as np
Import with alias
from . import module
Relative import
if __name__ == "__main__":
Run only when executed directly
pip install package
Install package
pip freeze > requirements.txt
Export dependencies
python -m venv env
Create virtual environment

Common Built-ins

len(obj)
Length of object
range(start, stop, step)
Generate sequence of numbers
zip(lst1, lst2)
Pair elements from two iterables
any(iterable)
True if any element is truthy
all(iterable)
True if all elements are truthy
min(iterable) / max(iterable)
Minimum / maximum value
sum(iterable)
Sum of all elements
abs(-5)
Absolute value
round(3.14159, 2)
Round to decimal places
dir(obj)
List attributes of object
help(func)
Get documentation

Useful Standard Library

import datetime datetime.datetime.now()
Current date and time
import re re.findall(r"\d+", text)
Find all pattern matches
import os os.environ.get("KEY")
Get environment variable
import sys sys.argv
Command-line arguments
from collections import Counter Counter(lst)
Count element frequencies
from collections import defaultdict dd = defaultdict(list)
Dict with default factory
import itertools itertools.chain(a, b)
Chain iterables together
import random random.choice(lst)
Random element from list
import hashlib hashlib.sha256(b"text").hexdigest()
SHA-256 hash
import subprocess subprocess.run(["ls", "-la"])
Run shell command
\xF0\x9F\x92\x99 Tip\xF0\x9F\x93\x9A Get Bundle \x244.99