Python Cheat Sheet
8 groups · 37 topics · Updated
In the examples, # → shows the result of that line. They are written for Python 3.10 or later.
Basics
The building blocks every program uses.
Variables
city = "Pune" # no keyword needed
score = 10
score = score + 5 # now 15
x, y = 1, 2 # two at once
PI = 3.14 # capitals: do not change- A name is created the first time you assign to it.
- Names use
snake_case:first_name, notfirstName.
Data types
| Value | Type |
|---|---|
"hello" |
str (text) |
42 |
int (whole number) |
3.14 |
float (decimal number) |
True, False |
bool |
None |
no value |
[1, 2, 3] |
list |
{"a": 1} |
dict |
(1, 2) |
tuple |
{1, 2} |
set |
type("hi") # → <class 'str'>
type(42) # → <class 'int'>
isinstance(42, int) # → TrueOperators
7 + 3 # → 10
7 / 2 # → 3.5
7 // 2 # → 3 (whole division)
7 % 3 # → 1 (remainder)
2 ** 3 # → 8 (power)
5 == 5.0 # → True
5 != 3 # → True
1 < 2 < 3 # → True (chained)
True and False # → False
True or False # → True
not True # → FalseShortcuts
age = 20
label = "adult" if age >= 18 else "child"
label # → 'adult'
name = None
name or "guest" # → 'guest'
n = 5
n += 1 # same as n = n + 1
n # → 6Truthy and falsy
These count as false: False, None, 0, "", [], {}, (), set(). Everything else is true.
bool("") # → False
bool("0") # → True
bool([]) # → False
bool([0]) # → Trueitems = []
if not items:
print("The list is empty")Print and input
print("Hi", "there") # Hi there
print("a", "b", sep="-") # a-b
print("no new line", end="")name = input("Your name? ")
age = int(input("Your age? "))inputalways returns text. Convert it withint()orfloat().
Strings and numbers
Working with text and with numbers.
Strings
s = "Hello, World"
len(s) # → 12
s.lower() # → 'hello, world'
s.upper() # → 'HELLO, WORLD'
s.replace("l", "L") # → 'HeLLo, WorLd'
s.split(", ") # → ['Hello', 'World']
"-".join(["a", "b"]) # → 'a-b'
" hi ".strip() # → 'hi'
s.startswith("He") # → True
"World" in s # → True
s.find("World") # → 7- Strings cannot be changed. Every method returns a new string.
- Single and double quotes mean the same.
Slicing
s = "Python"
s[0] # → 'P'
s[-1] # → 'n' (the last)
s[0:2] # → 'Py' (end not included)
s[2:] # → 'thon'
s[:-2] # → 'Pyth'
s[::-1] # → 'nohtyP' (reversed)Slicing works the same way on lists and tuples.
f-strings
name, price = "Tea", 2.5
f"{name} costs {price}"
# → 'Tea costs 2.5'
f"{price:.2f}" # → '2.50'
f"{1234567:,}" # → '1,234,567'
f"{0.25:.0%}" # → '25%'
f"{2 + 3}" # → '5'
f"{name!r}" # → "'Tea'"- Put
fbefore the quotes, and any expression inside{}.
Numbers
int("42") # → 42
float("3.5") # → 3.5
str(42) # → '42'
round(3.14159, 2) # → 3.14
abs(-5) # → 5
max(1, 5, 3) # → 5
sum([1, 2, 3]) # → 6
0.1 + 0.2 # → 0.30000000000000004import math
math.sqrt(16) # → 4.0
math.floor(3.7) # → 3
math.ceil(3.2) # → 4
math.pi # → 3.141592653589793- An
intcan be as large as you like. - A
floatis approximate. Round before comparing or showing it.
Logic and loops
Making decisions and repeating work.
If
score = 72
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
else:
grade = "C"
grade # → 'B'- A colon starts a block. Indentation, four spaces, says what is inside it.
- There are no brackets round the condition and no braces round the block.
Match
status = 404
match status:
case 200:
text = "OK"
case 404 | 410:
text = "Gone"
case _:
text = "Other"
text # → 'Gone'_matches anything.
Loops
for i in range(3):
print(i) # 0, 1, 2
for fruit in ["apple", "kiwi"]:
print(fruit)
pairs = enumerate(["a", "b"])
for i, letter in pairs:
print(i, letter) # 0 a, then 1 b
n = 3
while n > 0:
n -= 1list(range(5)) # → [0, 1, 2, 3, 4]
list(range(2, 5)) # → [2, 3, 4]
list(range(0, 10, 5)) # → [0, 5]breakleaves the loop.continueskips to the next turn.
Errors
try:
number = int("abc")
except ValueError:
number = 0
finally:
print("always runs")
number # → 0raise ValueError("Age must be positive")| Error | Cause |
|---|---|
ValueError |
Right type, wrong value: int("abc") |
TypeError |
Wrong type: "5" + 5 |
KeyError |
A dictionary key that is not there |
IndexError |
A list position that is not there |
AttributeError |
A method or field that does not exist |
NameError |
A variable that was never created |
Functions and classes
Naming a piece of work so it can be reused.
Functions
def greet(name, greeting="Hello"):
return f"{greeting}, {name}"
greet("Asha")
# → 'Hello, Asha'
greet("Asha", greeting="Hi")
# → 'Hi, Asha'- A function with no
returngives backNone. - Arguments can be passed by position or by name.
Flexible arguments
def total(*numbers):
return sum(numbers)
total(1, 2, 3) # → 6
def show(**options):
return options
show(size=2) # → {'size': 2}*numberscollects extra arguments into a tuple.**optionscollects named arguments into a dictionary.
Lambda and sorting
double = lambda x: x * 2
double(4) # → 8
words = ["kiwi", "fig", "apple"]
sorted(words)
# → ['apple', 'fig', 'kiwi']
sorted(words, key=len)
# → ['fig', 'kiwi', 'apple']
sorted(words, reverse=True)
# → ['kiwi', 'fig', 'apple']- A
lambdais a small function written in one line.
Classes
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof"
class Puppy(Dog):
def speak(self):
return super().speak() + "!"
Puppy("Rex").speak()
# → 'Rex says woof!'__init__runs when an object is created.- Every method takes
self, the object itself, as its first argument.
Dataclasses
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int = 0
p = Point(3)
p # → Point(x=3, y=0)
p == Point(3, 0) # → True- A short way to write a class that mostly holds data.
Type hints
def area(w: float, h: float) -> float:
return w * h
names: list[str] = []
age: int | None = None- Hints document the code and help your editor. Python does not enforce them.
Modules
import math
from math import sqrt
import numpy as np
from helpers import clean # your fileif __name__ == "__main__":
main()- The second form runs
main()only when the file is run directly, not when it is imported.
Lists, dicts and more
The built-in ways to hold many values.
Lists
nums = [3, 1, 2]
nums.append(4) # [3, 1, 2, 4]
nums.insert(0, 9) # [9, 3, 1, 2, 4]
nums.pop() # → 4
nums.remove(9) # [3, 1, 2]
nums.sort() # [1, 2, 3]
nums.reverse() # [3, 2, 1]
len(nums) # → 3
2 in nums # → True
nums.index(2) # → 1
sorted(nums) # → [1, 2, 3]nums.sort()changes the list.sorted(nums)returns a new one.
Comprehensions
A list, dictionary or set built from a loop in one line.
nums = [1, 2, 3, 4]
[n * 2 for n in nums]
# → [2, 4, 6, 8]
[n for n in nums if n % 2 == 0]
# → [2, 4]
{n: n * n for n in nums[:2]}
# → {1: 1, 2: 4}
{n % 2 for n in nums}
# → {0, 1}Dictionaries
user = {"name": "Asha", "age": 30}
user["name"] # → 'Asha'
user.get("email") # → None
user.get("email", "-") # → '-'
user["city"] = "Pune" # add or change
del user["age"]
"name" in user # → True
list(user.keys()) # → ['name', 'city']
list(user.values()) # → ['Asha', 'Pune']
for key, value in user.items():
print(key, value)user["email"]raisesKeyErrorif the key is missing.getdoes not.
Tuples and sets
point = (3, 4) # cannot be changed
point[0] # → 3
seen = {1, 2, 2, 3}
seen # → {1, 2, 3}
seen.add(4)
2 in seen # → True
{1, 2} | {2, 3} # → {1, 2, 3}
{1, 2} & {2, 3} # → {2}
{1, 2} - {2, 3} # → {1}| Type | Ordered | Can change | Repeats |
|---|---|---|---|
list |
Yes | Yes | Yes |
tuple |
Yes | No | Yes |
set |
No | Yes | No |
dict |
Yes | Yes | Keys: no |
Unpacking
x, y = (3, 4)
first, *rest = [1, 2, 3]
rest # → [2, 3]
a, b = 1, 2
a, b = b, a # swap
a # → 2
[*[1, 2], *[3]] # → [1, 2, 3]
{**{"a": 1}, "b": 2} # → {'a': 1, 'b': 2}Handy built-ins
names = ["Asha", "Ben"]
ages = [30, 25]
list(zip(names, ages))
# → [('Asha', 30), ('Ben', 25)]
any(a > 28 for a in ages) # → True
all(a > 28 for a in ages) # → False
min(ages) # → 25
list(reversed(ages)) # → [25, 30]
list(map(str, ages)) # → ['30', '25']Files and libraries
Reading data, and using code other people wrote.
Read and write files
with open("notes.txt") as file:
text = file.read()
with open("notes.txt") as file:
for line in file:
print(line.strip())
with open("out.txt", "w") as file:
file.write("Hello\n")| Mode | Does |
|---|---|
"r" |
Read. The default |
"w" |
Write, replacing what was there |
"a" |
Add to the end |
withcloses the file for you, even after an error.- Add
encoding="utf-8"to be safe with non-English text.
Paths
from pathlib import Path
path = Path("data") / "report.csv"
path.name # → 'report.csv'
path.suffix # → '.csv'
path.stem # → 'report'path.exists() # True or False
path.read_text() # the whole file
Path(".").glob("*.csv") # matching filesJSON
import json
text = json.dumps({"name": "Asha"})
text # → '{"name": "Asha"}'
data = json.loads(text)
data["name"] # → 'Asha'dumpsandloadswork with text.json.dump(data, file)andjson.load(file)work with an open file.
Dates
from datetime import date, timedelta
day = date(2026, 11, 14)
day.year # → 2026
day.isoformat() # → '2026-11-14'
day.strftime("%d %b %Y") # → '14 Nov 2026'
later = day + timedelta(days=7)
later.day # → 21date.today()Standard library
Modules that come with Python. Nothing to install.
| Module | For |
|---|---|
math |
Square roots, rounding, pi |
random |
Random numbers and choices |
datetime |
Dates and times |
json, csv |
Reading and writing data |
re |
Finding patterns in text |
pathlib |
File paths |
collections |
Counter, defaultdict |
itertools |
Combinations and chained loops |
from collections import Counter
Counter("hello").most_common(1)
# → [('l', 2)]Packages
python -m venv .venv
source .venv/bin/activate
pip install requests
pip freeze > requirements.txt
pip install -r requirements.txt- A virtual environment keeps each project's packages separate.
- On Windows, activate with
.venv\Scripts\activate.
Watch out
Mistakes that catch most people once.
Common mistakes
| Mistake | Fix |
|---|---|
= in a condition |
== compares, = assigns |
| Tabs mixed with spaces | Four spaces everywhere |
"5" + 5 |
int("5") + 5, or an f-string |
is to compare values |
==. Keep is for None |
def f(items=[]) |
items=None, then create the list inside |
b = a to copy a list |
b = a.copy() |
| Changing a list while looping over it | Loop over a copy: for x in items[:] |
Forgetting self in a method |
It is always the first argument |
Copies
a = [1, 2]
b = a # the same list
b.append(3)
a # → [1, 2, 3]
c = a.copy() # a separate list
c.append(4)
a # → [1, 2, 3]- Assigning a list or dictionary does not copy it. Both names point to one object.
Coming from JavaScript
| JavaScript | Python |
|---|---|
const, let |
Nothing: just assign |
null, undefined |
None |
true, false |
True, False |
&&, ||, ! |
and, or, not |
=== |
== |
// comment |
# comment |
{ } round a block |
A colon and indentation |
function |
def |
console.log() |
print() |
list.length |
len(list) |
| Array, object | list, dict |
`Hi ${name}` |
f"Hi {name}" |
See the JavaScript cheat sheet for the other side.
More help
The official pages to check details against.
Official documentation
| Topic | Page |
|---|---|
| Learning | The Python Tutorial |
| Built-in functions | Built-in Functions |
| Strings | String methods |
| Standard library | The Python Standard Library |
| Style | PEP 8: Style Guide |