Python Cheatsheet

Python Cheatsheet
x = 10

Variable assignment

Basics
x, y = 1, 2

Multiple assignment

Basics
type(x)

Get type of variable

Basics
int(x) / float(x) / str(x)

Type casting

Basics
print(f"Hello {name}")

F-string formatting

Basics
input("Enter: ")

Read user input

Basics
if x > 0: pass elif x == 0: pass else: pass

If/elif/else conditional

Basics
for i in range(10):

For loop with range

Basics
while condition:

While loop

Basics
x if condition else y

Ternary expression

Basics
try: ... except Exception as e: ... finally: ...

Try/except/finally

Basics
assert condition, "message"

Assertion check

Basics
s.upper() / s.lower()

Convert to upper/lower case

Strings
s.strip()

Remove leading/trailing whitespace

Strings
s.split(",")

Split string into list

Strings
",".join(lst)

Join list into string

Strings
s.replace("old", "new")

Replace substring

Strings
s.startswith("prefix")

Check if string starts with

Strings
s.find("sub")

Find substring index (-1 if not found)

Strings
s[1:5]

Slice string (index 1 to 4)

Strings
s.isdigit() / s.isalpha()

Check if digits/letters only

Strings
s.zfill(5)

Pad string with zeros

Strings
lst = [1, 2, 3]

Create a list

Lists
lst.append(4)

Add item to end

Lists
lst.insert(0, "first")

Insert at index

Lists
lst.pop() / lst.pop(0)

Remove last / at index

Lists
lst.remove(value)

Remove first occurrence of value

Lists
lst.sort() / sorted(lst)

Sort in-place / return sorted copy

Lists
lst.reverse()

Reverse list in-place

Lists
lst[1:3]

Slice list

Lists
len(lst)

Get list length

Lists
item in lst

Check if item exists in list

Lists
lst.index(value)

Get index of first occurrence

Lists
list(zip(a, b))

Zip two lists together

Lists
lst.extend([4, 5])

Extend list with another list

Lists
d = {"key": "value"}

Create a dictionary

Dicts
d["key"] / d.get("key", default)

Access value (with optional default)

Dicts
d.keys() / d.values() / d.items()

Get keys, values, or key-value pairs

Dicts
d.update({"k2": "v2"})

Merge another dict

Dicts
d.pop("key")

Remove and return value by key

Dicts
"key" in d

Check if key exists

Dicts
d | other_dict

Merge dicts (Python 3.9+)

Dicts
dict.fromkeys(["a","b"], 0)

Create dict with default values

Dicts
def fn(x, y=10):

Function with default parameter

Functions
def fn(*args, **kwargs):

Variadic arguments

Functions
lambda x: x * 2

Anonymous function

Functions
def fn() -> int:

Function with return type hint

Functions
@decorator def fn():

Apply decorator to function

Functions
map(fn, iterable)

Apply function to each item

Functions
filter(fn, iterable)

Filter items by function

Functions
functools.reduce(fn, iterable)

Reduce iterable to single value

Functions
[x**2 for x in range(10)]

List comprehension

Comprehensions
[x for x in lst if x > 0]

List comprehension with filter

Comprehensions
{k: v for k, v in items}

Dict comprehension

Comprehensions
{x for x in lst}

Set comprehension

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

Generator expression (lazy)

Comprehensions
class Dog: def __init__(self, name): self.name = name

Class with constructor

Classes
class Cat(Animal):

Class inheritance

Classes
@property def name(self):

Property getter

Classes
@staticmethod def create():

Static method (no self)

Classes
@classmethod def from_dict(cls, d):

Class method (cls instead of self)

Classes
def __str__(self):

String representation

Classes
def __len__(self):

Custom len() behavior

Classes
@dataclass class Point: x: float y: float

Dataclass (auto __init__, __repr__)

Classes
with open("f.txt") as f: text = f.read()

Read entire file

Files
with open("f.txt", "w") as f: f.write("text")

Write to file

Files
with open("f.txt") as f: for line in f:

Read file line by line

Files
import json json.loads(s) / json.dumps(obj)

Parse / stringify JSON

Files
import csv csv.reader(file)

Read CSV file

Files
from pathlib import Path Path("dir").mkdir(exist_ok=True)

Create directory

Files
Path("file.txt").exists()

Check if file exists

Files
Path("file.txt").read_text()

Read file as string (pathlib)

Files
import os

Import entire module

Modules
from os import path

Import specific item

Modules
import numpy as np

Import with alias

Modules
pip install package

Install package with pip

Modules
pip freeze > requirements.txt

Export dependencies

Modules
python -m venv .venv

Create virtual environment

Modules
if __name__ == "__main__":

Run only when executed directly

Modules
Showing 79 of 79 snippets

Free Online Python Cheatsheet

A searchable, filterable Python quick reference. Covers basics, strings, lists, dictionaries, functions, classes, comprehensions, file I/O, and common modules. Copy any snippet with one click.

About this cheatsheet

A comprehensive Python cheatsheet covering the most commonly used patterns and syntax.

  • 75+ practical Python snippets
  • 9 categories from basics to modules
  • Search across code and descriptions
  • Filter by category
  • One-click copy to clipboard
  • Covers Python 3.9+ features

100% free. No signup required. No data collected or sent anywhere.

Explore All Tools