🛠️ ToolsPilot
← Back to ToolsPilot

Python Cheat Sheet

Python quick reference. Data types, functions, comprehensions, and common modules. Bookmark this page or print it.

Data Types

x = 1 / 3.14 / "str" / TrueBasic types
[1, 2, 3]List
(1, 2, 3)Tuple
{"a": 1, "b": 2}Dict
{1, 2, 3}Set
NoneNull value

Comprehensions

[x*2 for x in range(10)]List comp
{k: v for k, v in items}Dict comp
{x for x in items if x > 0}Set comp
(x*2 for x in range(10))Generator

Functions

def f(a, b=1, *args, **kwargs):Function def
lambda x: x * 2Lambda
f"Hello {name}"F-string
@decoratorDecorator
yield valueGenerator

Common Modules

import os / os.pathOS operations
import json / json.dumps()JSON
import re / re.findall()Regex
import pathlib / Path()File paths
import datetime / datetime.now()Date/time
import collections / Counter()Collections

Error Handling

try: ... except: ...Try/except
try: ... except ValueError:Specific error
try: ... finally:Finally block
raise ValueError("msg")Raise error

File I/O

open("file", "r")Open file
with open("f") as fp:Context manager
fp.read() / fp.readlines()Read file
fp.write("text")Write file