glunty

Python Cheat Sheet

A searchable reference of core Python 3 syntax with a plain-English note on what each snippet does.

Common Python 3 snippets with a plain-English description of what each one does
Snippet What it does
print("Hello") Write text or a value to standard output.
x = 10 Assign a value to a variable; Python needs no type declaration.
int, float, str, bool The core scalar types: whole number, decimal number, text, and True or False.
type(x) Return the type of an object.
len(x) Return the number of items in a string, list, or other container.
input("Name: ") Read a line typed by the user and return it as a string.
f"hi {name}" An f-string inserts the value of name straight into the text.
# a comment Everything after the hash on a line is ignored by Python.
None The special value that stands for no value at all.
str(42) Convert a value to text; int() and float() convert the other way.
nums = [1, 2, 3] A list is an ordered, changeable sequence written in square brackets.
pair = (1, 2) A tuple is an ordered sequence that cannot be changed after it is made.
d = {"a": 1} A dict maps keys to values for fast lookup by key.
s = {1, 2, 3} A set holds unique unordered items.
nums[0] Index into a sequence; the first item sits at position zero.
a[1:3] Slice items from index 1 up to but not including index 3.
nums.append(4) Add one item to the end of a list.
nums.pop() Remove and return the last item of a list; pass an index to choose another.
d.keys() Return a view of every key in a dict.
d.values() Return a view of every value in a dict.
d.items() Return a view of the key and value pairs in a dict.
3 in nums Test whether a value is present in a container; the result is True or False.
if x > 0: Run the indented block only when the condition is true.
elif x == 0: Check another condition when the earlier if was false.
else: Run this block when no earlier condition matched.
for x in items: Loop over each item in a sequence in turn.
while x < 10: Keep repeating the block while the condition stays true.
range(5) Produce the numbers 0 through 4 for counting loops.
break Exit the nearest enclosing loop right away.
continue Skip to the next iteration of the loop.
enumerate(items) Yield each item together with its index, handy in a for loop.
zip(xs, ys) Pair up two sequences so a loop can walk them in parallel.
a if cond else b A ternary expression: give a when cond is true, otherwise b.
def greet(name): Define a function named greet that takes one argument.
return value Send a result back to the caller and end the function.
def f(x, n=1): Give a parameter a default so the caller may omit it.
def f(*args): Collect any number of positional arguments into a tuple named args.
def f(**kwargs): Collect any number of keyword arguments into a dict named kwargs.
square = lambda x: x * x A lambda is a small anonymous function written on one line.
"""Docstring.""" A string on the first line of a function documents what it does.
[x * 2 for x in nums] A list comprehension builds a new list by transforming each item.
{k: v for k, v in pairs} A dict comprehension builds a dict from key and value expressions.
{x for x in nums} A set comprehension builds a set of unique results.
(x * 2 for x in nums) A generator expression yields items lazily, one at a time.
[x for x in nums if x > 0] Add an if clause to keep only the items that pass a test.
"a,b".split(",") Split a string on a separator into a list of parts.
",".join(parts) Join a list of strings into one string with a separator between items.
" hi ".strip() Remove whitespace from both ends of a string.
s.replace("a", "b") Return a copy with every occurrence of one substring swapped for another.
s.upper() Return an uppercase copy; lower() gives a lowercase copy.
s.startswith("http") Test whether the string begins with the given prefix.
s.find("x") Return the index of the first match, or -1 when the substring is absent.
"{} and {}".format(a, b) Insert values into the placeholders of a format string.
with open("f.txt") as fh: Open a file and close it automatically when the block ends.
fh.read() Read the whole file into one string.
fh.readlines() Read every line of a file into a list.
open("f.txt", "w") Open a file for writing, replacing any existing contents.
fh.write("hi") Write a string to an open file.
import math Load a module so you can call its functions with the math. prefix.
from math import sqrt Import one name directly so you can call sqrt without a prefix.
try: Begin a block of code that might raise an exception.
except ValueError: Handle a specific exception type raised inside the try block.
finally: Run cleanup code whether or not an exception was raised.
raise ValueError("bad") Signal an error yourself by raising an exception.

Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.

What this tool does

This is a searchable quick reference for everyday Python 3 syntax, from printing and variables to collections, loops, functions, comprehensions, string methods, and file handling. Each row pairs a small snippet with a plain-English note on what it does. Type in the filter box to search across both columns, or tap a category button to focus on one area. The whole list is built into the page, so it works offline and sends nothing anywhere.

How to use it

Start typing in the Filter box. Entering split surfaces the string helpers; entering lambda jumps to anonymous functions; entering list shows the list operations. The category buttons (Basics, Collections, Control flow, Functions, Comprehensions, Strings, Files and modules) narrow the table to one area and combine with the text filter, so you can pick Control flow and type range to zero in on counting loops. Clear the box to see the full sheet again.

Common use cases

  • Recalling the exact syntax for something you use rarely, like enumerate or a dict comprehension.
  • Copying a correct snippet into your editor instead of guessing.
  • Teaching a beginner the difference between a list and a tuple.
  • Checking how *args and **kwargs are written before defining a flexible function.
  • Reviewing core Python before an interview or a new project.

Common pitfalls

  • Mutable default arguments. Writing def f(items=[]) reuses the same list on every call, so values pile up between calls. Default to None and create a fresh list inside the function instead.
  • Comparing with is instead of ==. Use == to compare values; is checks whether two names point at the exact same object, which is why it is right only for checks like x is None.
  • Integer versus float division. In Python 3, 10 / 3 gives a float, while 10 // 3 floors the result to an integer. Mixing them up leads to surprising numbers.
  • Inconsistent indentation. Python uses indentation to define blocks, so mixing tabs and spaces or misaligning a line raises an IndentationError. Pick spaces and keep every block at a steady width.

Frequently asked questions

What is a list comprehension in Python?
A list comprehension is a compact way to build a list from another sequence in a single expression. You write the value you want, then a for clause, and optionally an if clause to filter, all inside square brackets. For example, doubling the positive numbers in a list takes one line instead of a for loop with append calls. Comprehensions are usually faster and easier to read than the equivalent loop, though a plain loop is clearer once the logic grows complicated.
What is the difference between a list and a tuple?
A list is mutable, so you can add, remove, or change its items after creation, and you write it with square brackets. A tuple is immutable: once created its contents are fixed, and you write it with parentheses. Use a list when the collection will change over time, and a tuple for fixed groups of related values, such as coordinates, or as dictionary keys where a list is not allowed. Tuples are also slightly lighter and can signal that the data is meant to stay constant.
What are *args and **kwargs?
They are the two ways a function can accept a variable number of arguments. Writing *args collects any extra positional arguments into a tuple, so a function can take as many values as the caller passes. Writing **kwargs collects any extra keyword arguments into a dictionary of names and values. The names args and kwargs are only a convention; the stars are what matter. You can combine them, and you can also use a single star to forward one collection into another call.
How do f-strings work?
An f-string is a normal string with the letter f placed just before the opening quote. Inside it, any expression written between curly braces is evaluated and its result is dropped into the text, so an f-string can insert a name variable directly. You can call functions, do arithmetic, and apply format specifiers after a colon, for example to fix the number of decimal places. f-strings arrived in Python 3.6 and are the clearest and fastest way to build strings from values.
What does the with statement do?
The with statement manages a resource for you by opening it, running the indented block, and then cleaning up automatically, even if an error is raised inside the block. The most common use is opening files: with open handles closing the file for you, so you cannot forget and leak a file handle. Any object that supports the context manager protocol, such as file handles, locks, and network connections, can be used this way. It makes resource handling shorter and safer than a manual try and finally.
Does this cheat sheet send my searches anywhere?
No. The entire snippet list is baked into the page, and every search and category filter runs in your browser with JavaScript, so nothing you type leaves your device. There is no server call, no analytics, and no tracking. Open your browser DevTools and watch the Network tab while you search to confirm there are zero requests.

Embed this tool

Free for any use; attribution appreciated. Paste this on your site:

The embed runs the same tool that lives at this URL. No tracking; no ads inside the embed. Resize height as needed for your layout.

Cite this tool

For academic, journalistic, or technical references. Pick a format:

Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.

Embedded tool from glunty.com