·8 min read
Python Cheat Sheet
Essential Python syntax for everyday development. Covers data structures, functions, comprehensions, and common patterns.
Variables and Types
x = 10 # int
y = 3.14 # float
name = "Alice" # str
flag = True # bool
items = [1, 2, 3] # list
data = {"a": 1} # dict
coords = (1, 2) # tuple
unique = {1, 2, 3} # setStrings
s = "Hello, World!"
s.lower() # "hello, world!"
s.upper() # "HELLO, WORLD!"
s.split(", ") # ["Hello", "World!"]
s.replace("H", "J") # "Jello, World!"
s.strip() # remove whitespace
f"Name: {name}" # f-string formattingList Comprehensions
squares = [x**2 for x in range(10)] evens = [x for x in range(20) if x % 2 == 0] pairs = [(x, y) for x in range(3) for y in range(3)]
Dictionary Comprehensions
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Functions
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
def add(*args):
return sum(args)
def config(**kwargs):
return kwargsLambda Functions
square = lambda x: x ** 2 add = lambda a, b: a + b sorted(items, key=lambda x: x["name"])
Classes
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}"
class Employee(Person):
def __init__(self, name, age, salary):
super().__init__(name, age)
self.salary = salaryError Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected: {e}")
finally:
print("Always runs")File I/O
with open("file.txt", "r") as f:
content = f.read()
with open("file.txt", "w") as f:
f.write("Hello!")
with open("data.json", "r") as f:
data = json.load(f)Common Built-ins
len([1,2,3]) # 3 range(5) # 0,1,2,3,4 enumerate(items) # (0,a), (1,b)... zip(list1, list2) # paired items map(func, items) # apply func filter(func, items) # filter items sorted(items) # new sorted list any([False, True]) # True all([True, True]) # True
Useful Modules
import json # JSON parsing import os # OS operations import sys # System params import re # Regular expressions import datetime # Date/time import collections # defaultdict, Counter import pathlib # Path handling import requests # HTTP requests