Python Cheatsheet — Quick Reference Guide

Python ReferenceCheatsheetFree Lesson

Advertisement

Python Cheatsheet — Quick Reference Guide

A comprehensive quick reference for Python syntax, common patterns, and essential standard library modules. Keep this handy for daily coding.


Variables & Types

x = 42              # int
y = 3.14            # float
s = "hello"         # str
b = True            # bool
n = None            # NoneType
l = [1, 2, 3]       # list (mutable)
t = (1, 2)          # tuple (immutable)
d = {"k": "v"}      # dict
s = {1, 2, 3}       # set
fs = frozenset([1])  # frozenset (immutable set)

String Methods

"hello".upper()              # "HELLO"
"hello".lower()              # "hello"
"hello".title()              # "Hello"
"  hello  ".strip()          # "hello"
"hello world".split()        # ["hello", "world"]
"-".join(["a", "b", "c"])    # "a-b-c"
"hello".replace("l", "L")    # "heLLo"
"hello".find("ll")           # 2
"hello".startswith("he")     # True
"hello".endswith("lo")       # True
"hello123".isalnum()         # True
"123".isdigit()              # True
"hello".count("l")           # 2
f"Name: {name}, Age: {age}"  # f-string

List Operations

l = [1, 2, 3]
l.append(4)          # [1, 2, 3, 4]
l.insert(0, 0)       # [0, 1, 2, 3, 4]
l.extend([5, 6])     # [0, 1, 2, 3, 4, 5, 6]
l.pop()              # returns 6
l.pop(0)             # returns 0
l.remove(3)          # removes first 3
l.sort()             # in-place sort
l.reverse()          # in-place reverse
l.copy()             # shallow copy
l.index(2)           # index of first 2
l.count(1)           # occurrences of 1
l.clear()            # removes all elements

# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

Dictionary Operations

d = {"a": 1, "b": 2, "c": 3}
d.get("d", 0)           # 0 (default if key missing)
d.keys()                # dict_keys(['a', 'b', 'c'])
d.values()              # dict_values([1, 2, 3])
d.items()               # dict_items([('a', 1), ...])
d.update({"d": 4})      # add/update
d.pop("a")              # remove and return
d.popitem()             # remove last item
d.setdefault("e", 5)    # set if missing
d.clear()               # remove all

# Dict comprehension
square_dict = {x: x**2 for x in range(5)}

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 diff: {1, 2, 5, 6}
a.issubset(b)  # Subset check
a.issuperset(b)  # Superset check

Control Flow

# if/elif/else
if x > 0:
    print("positive")
elif x < 0:
    print("negative")
else:
    print("zero")

# Ternary operator
status = "adult" if age >= 18 else "minor"

# for loop
for i in range(10):           # 0 to 9
for i in range(2, 10, 2):     # 2, 4, 6, 8
for item in iterable:
for i, item in enumerate(iterable):
for a, b in zip(list1, list2):
for key, value in dict.items():
for item in reversed(list):
for item in sorted(list):

# while loop
while condition:
    break      # exit loop
    continue   # skip to next iteration
    pass       # do nothing

Functions

# Basic function
def greet(name: str) -> str:
    return f"Hello, {name}!"

# Default parameters
def greet(name: str, greeting: str = "Hello") -> str:
    return f"{greeting}, {name}!"

# *args and **kwargs
def func(*args, **kwargs):
    # args is a tuple
    # kwargs is a dict
    pass

# Lambda
square = lambda x: x ** 2
add = lambda a, b: a + b

# Decorator
import functools
def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

Common Imports

import os                    # Operating system interface
import sys                   # System parameters
import json                  # JSON encoding/decoding
import re                    # Regular expressions
import math                  # Math functions
import random                # Random numbers
import datetime              # Date and time
import logging               # Logging
import unittest              # Testing
from pathlib import Path     # File paths
from typing import Optional, List, Dict, Union  # Type hints
from collections import Counter, defaultdict, namedtuple
from functools import lru_cache, partial, reduce
from itertools import chain, groupby, islice, product
from contextlib import contextmanager, suppress, redirect_stdout

File I/O

# Read entire file
with open("file.txt") as f:
    data = f.read()

# Read lines
with open("file.txt") as f:
    lines = f.readlines()  # List of lines
    for line in f:          # Memory-efficient
        process(line)

# Write
with open("file.txt", "w") as f:
    f.write("content")

# Append
with open("file.txt", "a") as f:
    f.write("more content")

# Read/Write binary
with open("file.bin", "rb") as f:
    data = f.read()

Error Handling

try:
    risky_operation()
except ValueError as e:
    print(f"Value error: {e}")
except (TypeError, KeyError) as e:
    print(f"Type/Key error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
    raise  # Re-raise the exception
else:
    print("Success!")  # Runs if no exception
finally:
    cleanup()  # Always runs

# Raise exceptions
raise ValueError("Invalid value")
raise TypeError("Wrong type")

Virtual Environment

# Create
python -m venv venv

# Activate (Linux/Mac)
source venv/bin/activate

# Activate (Windows)
venv\Scripts\activate

# Install packages
pip install -r requirements.txt

# Save dependencies
pip freeze > requirements.txt

# Deactivate
deactivate

Common Patterns

# Swap variables
a, b = b, a

# Unpack list
first, *middle, last = [1, 2, 3, 4, 5]

# Check membership
if item in collection:
    pass

# Count occurrences
from collections import Counter
counts = Counter(["a", "b", "a", "c"])  # {'a': 2, 'b': 1, 'c': 1}

# Default dict
from collections import defaultdict
dd = defaultdict(list)
dd["key"].append("value")

# Named tuple
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)

# Chained comparison
if 0 < x < 100:
    pass

# Walrus operator (Python 3.8+)
if (n := len(data)) > 10:
    print(f"Too long: {n}")

Key Takeaways

  1. Keep this cheatsheet handy for quick reference
  2. Practice patterns until they become second nature
  3. Read Python source code to learn idioms
  4. Use help() and dir() for interactive help
  5. The Python docs are excellent — use them!

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement