Free Python cheat sheet

Python cheat sheet

The Python syntax you reach for every day, on one page: types, strings, lists, dicts, control flow, functions, and comprehensions.

Variables and typesStringsListsDictionariesControl flowFunctionsComprehensions

← All cheat sheets

Python Cheat Sheet

Quick reference from FreeCodingCourses.com

Variables and types

x = 5
int. No type declaration needed.
pi = 3.14
float.
name = "Ada"
str. Single or double quotes both work.
ok = True
bool is True or False, capitalized.
nothing = None
the null value in Python.
type(x)
check a value's type at runtime.

Strings

f"Hi {name}, you are {age}"
f-string: inline any expression in {}.
s.upper() s.lower() s.strip()
case change and trim whitespace.
s.split(",")
split into a list on a separator.
", ".join(items)
join a list of strings back together.
s.replace("a", "b")
swap every occurrence.
s[0] s[-1] s[1:4]
index and slice. -1 is the last char.

Lists

nums = [1, 2, 3]
ordered, mutable.
nums.append(4)
add to the end.
nums.pop() nums.pop(0)
remove and return last, or by index.
len(nums)
count items.
nums[1:3] nums[::-1]
slice, and reverse with [::-1].
sorted(nums) nums.sort()
sorted() returns a copy, .sort() edits in place.

Dictionaries

user = {"name": "Ada", "age": 36}
key/value pairs.
user["name"]
read a value by key.
user.get("email", "n/a")
read with a fallback if the key is missing.
user["email"] = "[email protected]"
add or update a key.
user.keys() user.values() user.items()
iterate keys, values, or pairs.
"name" in user
check if a key exists.

Control flow

if x > 0: ... elif x == 0: ... else: ...
indentation defines blocks. Four spaces.
for item in items:
loop over any iterable.
for i in range(5):
0, 1, 2, 3, 4.
while cond:
loop until cond is False.
break continue
exit the loop, or skip to the next pass.
for i, v in enumerate(items):
index and value together.

Functions

def add(a, b): return a + b
define and return.
def greet(name, greeting='Hi'):
default argument values.
def total(*args, **kwargs):
any number of positional / keyword args.
square = lambda n: n * n
small anonymous function.
add(2, b=3)
call positionally or by keyword.

Comprehensions

[n * 2 for n in nums]
build a list in one line.
[n for n in nums if n > 0]
filter while you build.
{k: v for k, v in pairs}
dict comprehension.
{n % 3 for n in nums}
set comprehension (unique values).

Unlock the full Python cheat sheet

You're seeing 2 of 7 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.

No spam, unsubscribe anytime. See our privacy policy.

Python questions, answered

Is this Python cheat sheet for Python 3?

Yes, everything here is Python 3, which is the version you should be learning. Python 2 reached end of life in 2020. The big day-to-day difference you will notice is print(), which is a function with parentheses in Python 3.

How do I actually learn Python, not just reference it?

A cheat sheet is for recall once you know the ideas. To learn from zero, work through a structured free course and build small programs as you go. freeCodeCamp's Python courses and Harvard's CS50 are strong free starting points.

What is the difference between a list and a tuple?

A list uses square brackets and can be changed after you make it. A tuple uses parentheses, like point = (3, 4), and cannot be changed. Use a tuple when the group of values should stay fixed.

Where to go next