Python Cheat Sheet
Last updated
Basics & printing
Variables, comments, and getting output on the screen.
| Operation | Syntax |
|---|---|
| Assign a variable | x = 10 |
| Print a value | print("Hello") |
| Print multiple values | print("x =", x) |
| Single-line comment | # this is a comment |
| Read input | name = input("Name: ") |
| Multiple assignment | a, b = 1, 2 |
| Check the type | type(x) |
Data types
The core built-in types and how to convert between them.
| Type | Example |
|---|---|
Integer (int) | age = 25 |
Float (float) | price = 9.99 |
String (str) | name = "Ada" |
Boolean (bool) | is_active = True |
| List | nums = [1, 2, 3] |
| Tuple (immutable) | point = (4, 5) |
| Dictionary | user = {"id": 1} |
| None / convert | value = None, int("7"), str(42) |
Strings & f-strings
Format and manipulate text.
| Operation | Syntax |
|---|---|
| f-string interpolation | f"Hi {name}, you are {age}" |
| Length | len(text) |
| Upper / lower case | text.upper(), text.lower() |
| Strip whitespace | text.strip() |
| Replace | text.replace("a", "b") |
| Split into a list | text.split(",") |
| Join a list | ", ".join(items) |
| Slice characters | text[0:3] |
| Contains | "py" in text |
Lists
Ordered, mutable sequences.
| Operation | Syntax |
|---|---|
| Create | nums = [1, 2, 3] |
| Access by index | nums[0], last: nums[-1] |
| Add to the end | nums.append(4) |
| Insert at index | nums.insert(0, 9) |
| Remove a value | nums.remove(2) |
| Pop by index | nums.pop() |
| Slice | nums[1:3] |
| Sort in place | nums.sort() |
| Length | len(nums) |
Dictionaries
Key-value pairs for fast lookups.
| Operation | Syntax |
|---|---|
| Create | user = {"id": 1, "name": "Ada"} |
| Access a value | user["name"] |
| Safe access (no error) | user.get("age", 0) |
| Add / update a key | user["age"] = 25 |
| Delete a key | del user["age"] |
| Check for a key | "name" in user |
| Iterate keys & values | for k, v in user.items(): |
| All keys / values | user.keys(), user.values() |
Control flow
Conditionals and loops.
| Operation | Syntax |
|---|---|
| If / elif / else | if x > 0: … elif x == 0: … else: |
| For loop over a list | for item in items: |
| For loop over a range | for i in range(5): |
| While loop | while x < 10: |
| Loop with index | for i, v in enumerate(items): |
| Break / continue | break, continue |
| Ternary expression | y = 1 if x else 0 |
Functions
Define reusable blocks of code.
| Operation | Syntax |
|---|---|
| Define a function | def greet(name): |
| Return a value | return name.upper() |
| Default argument | def greet(name="World"): |
| Keyword arguments | greet(name="Ada") |
| Variable args | def f(*args, **kwargs): |
| Lambda (anonymous) | square = lambda x: x * x |
| Docstring | """What this does.""" |
List comprehensions
Build lists, sets, and dicts in a single expression.
| Operation | Syntax |
|---|---|
| Map a list | [x * 2 for x in nums] |
| Filter a list | [x for x in nums if x > 0] |
| Map and filter | [x * 2 for x in nums if x > 0] |
| Nested loop | [(i, j) for i in a for j in b] |
| Set comprehension | {x % 3 for x in nums} |
| Dict comprehension | {k: v * 2 for k, v in d.items()} |
Common built-ins & standard library
Functions and modules you use constantly.
| Function | What it does |
|---|---|
len(x) | Length of a string, list, or dict |
range(start, stop, step) | Sequence of numbers |
sum(nums) / max() / min() | Total, largest, smallest |
sorted(items) | Return a new sorted list |
zip(a, b) | Pair up two iterables |
map(f, items) / filter(f, items) | Apply / keep by a function |
import math | Math functions, e.g. math.sqrt(9) |
import random | Random values, e.g. random.randint(1, 6) |
The Python syntax, data types, and built-ins you reach for most, on one page. This Python cheat sheet is a quick reference for everyday Python 3 - printing, strings and f-strings, lists and dictionaries, control flow, functions, and comprehensions.
Everything here is standard Python 3 that runs anywhere. Copy what you need, or try any snippet live in the Python playground - a real interpreter in your browser, nothing to install. Want to learn from scratch? Coddy's free interactive Python course takes you from the basics to functions and classes.
Python cheat sheet FAQ
Is this Python cheat sheet free?
What is the difference between a list and a tuple in Python?
[1, 2, 3]. A tuple is immutable, written with parentheses: (1, 2, 3), so once created it cannot change. Use a list for a collection that grows or changes, and a tuple for fixed groups of values like coordinates or a row of data.What is an f-string in Python?
f that lets you embed expressions directly inside curly braces, like f"Hello {name}, you have {count} messages". Python evaluates each expression and inserts its value. They are the clearest and fastest way to format strings in Python 3.6+.