coderef

Python Quick Reference

Everyday Python: variables, strings, lists, dicts, control flow, functions, classes, files and errors.

11 sections · 92 snippets · updated Oct 14, 2026

Click any snippet to copy it.

Basics

Variables, output, input and comments.

  • Assign a variable
  • Assign several at once
  • Swap two variables
  • Print a value
  • Print without a newline
  • Read input
  • Comment
  • Check a type

Numbers & conversion

Arithmetic and converting between types.

  • Integer division
  • Remainder
  • Power
  • Round
  • String to number
  • Number to string
  • Min / max / sum
  • Absolute value

Strings

Formatting and manipulating text.

  • Format with an f-string
  • Format a number
  • Length
  • Upper / lower case
  • Trim whitespace
  • Replace
  • Split / join
  • Find a substring
  • Starts / ends with
  • Slice
  • Multi-line string

Lists

Ordered, mutable sequences.

  • Create
  • Access first / last
  • Add to the end
  • Add many
  • Insert at an index
  • Remove by value
  • Remove by index
  • Sort
  • Sort by a key
  • Reverse
  • Index of a value
  • Slice
  • List comprehension
  • Loop with index
  • Loop over two lists

Tuples & sets

Immutable sequences and unique collections.

  • Create a tuple
  • Unpack
  • Create a set
  • Remove duplicates
  • Add / remove
  • Union / intersection / difference

Dictionaries

Key–value maps.

  • Create
  • Get a value
  • Set a value
  • Delete a key
  • Check a key
  • Loop over pairs
  • Keys / values
  • Merge
  • Dict comprehension
  • Count items
  • Default values

Control flow

Conditions and loops.

  • If / elif / else
  • Ternary
  • For loop over a range
  • While loop
  • Break / continue
  • Match (3.10+)
  • Any / all

Functions

Defining and calling functions.

  • Define
  • Default argument
  • Keyword arguments
  • Variable arguments
  • Type hints
  • Lambda
  • Map / filter

Classes

Objects and data classes.

  • Define a class
  • Create an instance
  • Inheritance
  • Data class
  • String representation
  • Property

Errors & files

Exceptions and reading/writing files.

  • Catch an exception
  • Raise an exception
  • Read a whole file
  • Read line by line
  • Write a file
  • JSON
  • Paths

Modules & tooling

Imports, packages and running code.

  • Import
  • Run only as a script
  • Create a virtual environment
  • Install a package
  • Current date and time
  • Random

← All quick references