Skip to content
AgileLogics

Python Cheat Sheet

Learn Python from the basics →

Variables

x = "value"
Declare a variable (type inferred)
f"Hello, {name}"
f-string interpolation
type(x)
Get a variable's type

Lists & Dicts

[1, 2, 3]
List literal
{"k": "v"}
Dict literal
len(x)
Length of a list/dict/string
[x * 2 for x in arr]
List comprehension
sorted(arr)
Return a sorted copy

Strings

len(s)
String length
s.lower() / s.upper()
Change case
"x" in s
Check for a substring
s.strip()
Remove surrounding whitespace
s.split(",")
Split into a list

Control Flow

if / elif / else
Conditional branching
for x in arr:
Loop over values
for k, v in d.items():
Loop over dict entries

Functions

def f(x: str) -> str: ...
Typed function
lambda x: x * 2
Anonymous function
f(name="Ada")
Keyword argument

Classes

class User:\n def __init__(self, name): self.name = name
Class with constructor
User("Ada")
Instantiate
class Admin(User): pass
Inheritance

Exceptions

try: ...\nexcept ValueError as e: ...
Catch a specific exception
finally: ...
Always runs, error or not
raise ValueError("msg")
Raise an exception

File Handling

with open("f.txt") as file: ...
Open a file, auto-closed
file.read()
Read entire file contents
file.write("text")
Write to a file ("w" mode)

JSON & APIs

json.dumps(data)
Python dict/list -> JSON string
json.loads(text)
JSON string -> Python dict/list
requests.get(url).json()
Fetch and parse a JSON API response

Packages & Environments

python3 -m venv venv
Create a virtual environment
pip install requests
Install a package
pip freeze > requirements.txt
Record installed package versions