Python Cheat Sheet: Commands You'll Use Every Day

Whether you're just starting out or you've been writing Python for a while, there are certain commands and patterns you reach for constantly. This cheat sheet collects all of them in one place so you can find what you need fast.
Bookmark this page. You'll be back.
Variables and Data Types
Python is dynamically typed, so you don't declare types explicitly. Here are the core data types you'll work with daily:
# Numbers
age = 30
price = 19.99
result = 10 + 3j # complex number
# Strings
name = "Alice"
multiline = """This string
spans multiple lines"""
# Booleans
is_active = True
is_deleted = False
# None
value = None
# Type checking
type(age) # <class 'int'>
isinstance(age, int) # True
Strings
Strings are one of the most used data types. Here's everything you need:
Creating and Formatting
# f-strings (Python 3.6+)
name = "Alice"
greeting = f"Hello, {name}!"
price = 49.99
formatted = f"Total: ${price:.2f}"
# String methods
"hello world".upper() # "HELLO WORLD"
"HELLO WORLD".lower() # "hello world"
"hello world".title() # "Hello World"
"hello world".capitalize() # "Hello world"
" hello ".strip() # "hello"
" hello ".lstrip() # "hello "
" hello ".rstrip() # " hello"
Searching and Checking
"hello world".find("world") # 6
"hello world".index("world") # 6 (raises ValueError if not found)
"hello world".count("l") # 3
"hello world".startswith("hello") # True
"hello world".endswith("world") # True
"hello123".isalnum() # True
"hello".isalpha() # True
"12345".isdigit() # True
Modifying and Splitting
"hello world".replace("world", "Python") # "hello Python"
"a,b,c,d".split(",") # ["a", "b", "c", "d"]
"hello world".split() # ["hello", "world"]
", ".join(["a", "b", "c"]) # "a, b, c"
# Slicing
text = "Python"
text[0] # "P"
text[-1] # "n"
text[0:3] # "Pyt"
text[:3] # "Pyt"
text[3:] # "hon"
text[::-1] # "nohtyP" (reverse)
Lists
Lists are mutable, ordered sequences. You'll use them everywhere:
Creating and Accessing
fruits = ["apple", "banana", "cherry"]
numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]
empty = []
# Accessing
fruits[0] # "apple"
fruits[-1] # "cherry"
fruits[1:3] # ["banana", "cherry"]
len(fruits) # 3
Adding and Removing
fruits.append("date") # Add to end
fruits.insert(1, "blueberry") # Insert at index
fruits.extend(["fig", "grape"]) # Add multiple items
fruits.remove("banana") # Remove by value
fruits.pop() # Remove and return last item
fruits.pop(0) # Remove and return item at index
del fruits[0] # Delete by index
fruits.clear() # Remove all items
Sorting and Searching
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort() # Sort in place: [1, 1, 2, 3, 4, 5, 6, 9]
numbers.sort(reverse=True) # Sort descending
sorted_nums = sorted(numbers) # Return new sorted list (original unchanged)
numbers.index(4) # Find index of value
numbers.count(1) # Count occurrences
numbers.reverse() # Reverse in place
List Comprehensions
# Basic
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# With transformation
words = ["hello", "world"]
upper_words = [w.upper() for w in words]
# ["HELLO", "WORLD"]
# Nested
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
Dictionaries
Dictionaries store key-value pairs. They're fast for lookups and essential for structured data:
Creating and Accessing
user = {"name": "Alice", "age": 30, "email": "alice@example.com"}
empty_dict = {}
from_keys = dict.fromkeys(["a", "b", "c"], 0) # {"a": 0, "b": 0, "c": 0}
# Accessing
user["name"] # "Alice" (raises KeyError if missing)
user.get("name") # "Alice"
user.get("phone", "N/A") # "N/A" (default if missing)
Modifying
user["age"] = 31 # Update value
user["phone"] = "555-0123" # Add new key
user.update({"age": 32, "city": "NYC"}) # Update multiple
del user["email"] # Delete key
removed = user.pop("phone") # Remove and return value
user.setdefault("role", "user") # Set only if key doesn't exist
Iterating
# Keys, values, and items
for key in user:
print(key)
for value in user.values():
print(value)
for key, value in user.items():
print(f"{key}: {value}")
# Check membership
"name" in user # True
"salary" not in user # True
Dictionary Comprehensions
# Basic
squares = {x: x**2 for x in range(6)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Filtering
high_scores = {k: v for k, v in scores.items() if v > 80}
# Swapping keys and values
inverted = {v: k for k, v in original.items()}
Tuples and Sets
Tuples (Immutable Sequences)
point = (3, 4)
single = (42,) # Note the trailing comma
x, y = point # Unpacking: x=3, y=4
# Tuples are immutable but useful for:
coordinates = [(1, 2), (3, 4), (5, 6)] # List of tuples
person = ("Alice", 30, "NYC")
name, age, city = person # Unpacking
Sets (Unique Collections)
colors = {"red", "green", "blue"}
from_list = set([1, 2, 2, 3, 3, 3]) # {1, 2, 3}
colors.add("yellow")
colors.remove("red") # Raises KeyError if missing
colors.discard("red") # No error if missing
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # Union: {1, 2, 3, 4, 5, 6}
a & b # Intersection: {3, 4}
a - b # Difference: {1, 2}
a ^ b # Symmetric difference: {1, 2, 5, 6}
Loops and Control Flow
For Loops
# Iterating over a list
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
# With index
for i, fruit in enumerate(["apple", "banana", "cherry"]):
print(f"{i}: {fruit}")
# Range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)
# Iterating over two lists at once
names = ["Alice", "Bob"]
ages = [30, 25]
for name, age in zip(names, ages):
print(f"{name} is {age}")
While Loops
count = 0
while count < 5:
print(count)
count += 1
# Break and continue
for i in range(10):
if i == 3:
continue # Skip 3
if i == 7:
break # Stop at 7
print(i)
Conditional Expressions
# If/elif/else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
# Ternary operator
status = "adult" if age >= 18 else "minor"
# Match statement (Python 3.10+)
match command:
case "quit":
exit()
case "hello":
print("Hi!")
case _:
print("Unknown command")
Functions
Defining Functions
def greet(name):
return f"Hello, {name}!"
# Default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# Multiple return values
def get_dimensions():
return 1920, 1080
width, height = get_dimensions()
Args and Kwargs
# *args: variable positional arguments
def add(*numbers):
return sum(numbers)
add(1, 2, 3) # 6
# **kwargs: variable keyword arguments
def create_user(**kwargs):
return kwargs
create_user(name="Alice", age=30)
# {"name": "Alice", "age": 30}
# Combined
def func(required, *args, **kwargs):
pass
Lambda Functions
# Short anonymous functions
square = lambda x: x**2
square(5) # 25
# Common use with sorted, map, filter
names = ["Charlie", "Alice", "Bob"]
sorted(names, key=lambda x: len(x))
# ["Bob", "Alice", "Charlie"]
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
# [2, 4, 6, 8, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4]
Classes
Basic Class
class Dog:
# Class variable (shared by all instances)
species = "Canis familiaris"
def __init__(self, name, age):
# Instance variables
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
def __str__(self):
return f"{self.name}, {self.age} years old"
# Usage
dog = Dog("Rex", 5)
print(dog.bark()) # "Rex says woof!"
print(dog) # "Rex, 5 years old"
Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Cat(Animal):
def speak(self):
return f"{self.name} says meow!"
class Dog(Animal):
def speak(self):
return f"{self.name} says woof!"
cat = Cat("Whiskers")
cat.speak() # "Whiskers says meow!"
Dataclasses (Python 3.7+)
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
z: float = 0.0
def distance_from_origin(self):
return (self.x**2 + self.y**2 + self.z**2) ** 0.5
p = Point(3, 4)
print(p) # Point(x=3, y=4, z=0.0)
print(p.distance_from_origin()) # 5.0
File I/O
Reading Files
# Read entire file
with open("data.txt", "r") as f:
content = f.read()
# Read line by line
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
# Read all lines into a list
with open("data.txt", "r") as f:
lines = f.readlines()
Writing Files
# Write (overwrites existing content)
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
# Append
with open("output.txt", "a") as f:
f.write("Another line\n")
# Write multiple lines
lines = ["line 1\n", "line 2\n", "line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
Working with CSV
import csv
# Reading CSV
with open("data.csv", "r") as f:
reader = csv.reader(f)
header = next(reader) # Skip header row
for row in reader:
print(row)
# Reading CSV as dictionaries
with open("data.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["age"])
# Writing CSV
with open("output.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["name", "age"])
writer.writerow(["Alice", 30])
Working with JSON
import json
# Read JSON file
with open("data.json", "r") as f:
data = json.load(f)
# Write JSON file
with open("output.json", "w") as f:
json.dump(data, f, indent=2)
# Convert between JSON strings and Python objects
json_string = json.dumps({"name": "Alice", "age": 30})
parsed = json.loads(json_string)
Error Handling
# Try/except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except (TypeError, ValueError) as e:
print(f"Error: {e}")
else:
print("No errors occurred")
finally:
print("This always runs")
# Raising exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
Common Libraries Quick Reference
os and pathlib (File System)
import os
from pathlib import Path
# os module
os.getcwd() # Current directory
os.listdir(".") # List directory contents
os.path.exists("file.txt") # Check if path exists
os.path.join("dir", "file") # Join path components
os.makedirs("a/b/c", exist_ok=True) # Create nested dirs
# pathlib (modern alternative)
p = Path(".")
list(p.glob("*.py")) # Find all .py files
p / "subdir" / "file.txt" # Join paths with /
Path("file.txt").exists() # Check existence
Path("file.txt").read_text() # Read file contents
Path("dir").mkdir(parents=True, exist_ok=True)
datetime
from datetime import datetime, timedelta
now = datetime.now()
today = datetime.today().date()
# Formatting
now.strftime("%Y-%m-%d %H:%M:%S") # "2026-02-14 10:30:00"
now.strftime("%B %d, %Y") # "February 14, 2026"
# Parsing
dt = datetime.strptime("2026-02-14", "%Y-%m-%d")
# Arithmetic
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
diff = datetime(2026, 12, 31) - now
print(diff.days)
collections
from collections import Counter, defaultdict, namedtuple
# Counter: count occurrences
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
count = Counter(words)
count.most_common(2) # [("apple", 3), ("banana", 2)]
# defaultdict: dict with default values
groups = defaultdict(list)
for name, dept in [("Alice", "eng"), ("Bob", "eng"), ("Charlie", "sales")]:
groups[dept].append(name)
# {"eng": ["Alice", "Bob"], "sales": ["Charlie"]}
# namedtuple: lightweight data container
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4
itertools
from itertools import chain, product, combinations, groupby
# chain: combine multiple iterables
list(chain([1, 2], [3, 4], [5])) # [1, 2, 3, 4, 5]
# product: cartesian product
list(product("AB", "12")) # [("A","1"),("A","2"),("B","1"),("B","2")]
# combinations
list(combinations([1, 2, 3], 2)) # [(1,2), (1,3), (2,3)]
# groupby (data must be sorted by key)
data = [("A", 1), ("A", 2), ("B", 3)]
for key, group in groupby(data, key=lambda x: x[0]):
print(key, list(group))
Useful Built-in Functions
These are the Python built-ins you'll use most often:
# Math
abs(-5) # 5
round(3.14159, 2) # 3.14
min(1, 2, 3) # 1
max(1, 2, 3) # 3
sum([1, 2, 3]) # 6
pow(2, 10) # 1024
# Type conversion
int("42") # 42
float("3.14") # 3.14
str(42) # "42"
bool(0) # False
list("abc") # ["a", "b", "c"]
tuple([1, 2, 3]) # (1, 2, 3)
set([1, 2, 2, 3]) # {1, 2, 3}
dict([("a", 1)]) # {"a": 1}
# Iteration helpers
len([1, 2, 3]) # 3
range(5) # 0, 1, 2, 3, 4
enumerate(["a", "b", "c"]) # (0,"a"), (1,"b"), (2,"c")
zip([1, 2], ["a", "b"]) # (1,"a"), (2,"b")
reversed([1, 2, 3]) # 3, 2, 1
sorted([3, 1, 2]) # [1, 2, 3]
# Functional
map(str, [1, 2, 3]) # "1", "2", "3"
filter(bool, [0, 1, "", "a"]) # 1, "a"
any([False, True, False]) # True
all([True, True, False]) # False
Frequently Asked Questions
What version of Python should I use?
Use Python 3.10 or newer for the best experience. It gives you access to modern features like structural pattern matching (match/case), improved error messages, and the latest standard library additions. Python 2 has been end-of-life since 2020.
How do I check my Python version?
Run python --version or python3 --version in your terminal. Inside a script, you can use import sys; print(sys.version).
What's the difference between a list and a tuple?
Lists are mutable (you can add, remove, and change elements), while tuples are immutable (once created, they can't be changed). Use lists when your data needs to change and tuples when it shouldn't, like dictionary keys or function return values.
When should I use a dictionary vs. a list?
Use a dictionary when you need to look up values by a key (like a name or ID). Use a list when you have an ordered collection of items and access them by position. Dictionary lookups are O(1) on average, while searching a list is O(n).
What does if __name__ == "__main__" do?
It checks whether the current file is being run directly (not imported as a module). Code inside this block only executes when you run the file directly with python script.py, not when another file imports it.
def main():
print("Running directly")
if __name__ == "__main__":
main()

