Bestseller #1
Bestseller #2
Bestseller #3
Bestseller #4
Bestseller #5
Bestseller #6
Bestseller #7
🐍 Python Cheat Sheet
Quick reference guide for Python essentials
Basics
Variables & Data Types
# Variables (no declaration needed)
x = 5 # int
y = 3.14 # float
name = "Alice" # str
is_valid = True # bool
items = [1, 2, 3] # list
coords = (10, 20) # tuple
unique = {1, 2, 3} # set
person = {"name": "Bob"} # dict
nothing = None # NoneType
String Operations
s = "Hello World"
s.lower() # "hello world"
s.upper() # "HELLO WORLD"
s.strip() # remove whitespace
s.replace("H", "J") # "Jello World"
s.split() # ["Hello", "World"]
s.startswith("He") # True
s.endswith("ld") # True
len(s) # 11
s[0] # "H"
s[-1] # "d"
s[0:5] # "Hello"
# F-strings (Python 3.6+)
name = "Alice"
age = 30
f"My name is {name} and I'm {age}"
f"{age:.2f}" # format to 2 decimals
Type Conversion
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
list("abc") # ['a', 'b', 'c']
tuple([1, 2]) # (1, 2)
Data Structures
Lists (mutable, ordered)
fruits = ["apple", "banana", "cherry"]
# Access
fruits[0] # "apple"
fruits[-1] # "cherry"
fruits[1:3] # ["banana", "cherry"]
# Modify
fruits.append("orange") # add to end
fruits.insert(1, "kiwi") # insert at index
fruits.remove("banana") # remove by value
fruits.pop() # remove & return last
fruits.pop(0) # remove & return at index
del fruits[0] # delete by index
# Operations
len(fruits) # length
fruits.sort() # sort in place
sorted(fruits) # return sorted copy
fruits.reverse() # reverse in place
fruits.count("apple") # count occurrences
fruits.index("cherry") # find index
"apple" in fruits # True/False
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
Tuples (immutable, ordered)
point = (10, 20)
x, y = point # unpacking
single = (1,) # single element tuple needs comma
Sets (mutable, unordered, unique)
s = {1, 2, 3, 3} # {1, 2, 3}
s.add(4) # add element
s.remove(2) # remove (error if not exists)
s.discard(2) # remove (no error)
# Operations
a = {1, 2, 3}
b = {3, 4, 5}
a | b # union: {1, 2, 3, 4, 5}
a & b # intersection: {3}
a - b # difference: {1, 2}
a ^ b # symmetric diff: {1, 2, 4, 5}
Dictionaries (key-value pairs)
person = {"name": "Alice", "age": 30}
# Access
person["name"] # "Alice"
person.get("age") # 30
person.get("city", "NYC") # default value
# Modify
person["age"] = 31 # update
person["city"] = "NYC" # add new key
del person["age"] # delete key
person.pop("name") # remove & return
# Operations
person.keys() # dict_keys(['name', 'age'])
person.values() # dict_values(['Alice', 30])
person.items() # dict_items([('name', 'Alice'), ...])
"name" in person # True
# Dict comprehension
squares = {x: x**2 for x in range(5)}
Control Flow
If Statements
if x > 0:
print("positive")
elif x < 0:
print("negative")
else:
print("zero")
# Ternary operator
result = "even" if x % 2 == 0 else "odd"
Loops
# For loop
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)
for fruit in fruits:
print(fruit)
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# While loop
i = 0
while i < 5:
print(i)
i += 1
# Break and continue
for i in range(10):
if i == 3:
continue # skip to next iteration
if i == 8:
break # exit loop
print(i)
Match Statement (Python 3.10+)
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case _:
print("Unknown")
Functions
Basic Functions
def greet(name):
return f"Hello, {name}!"
def add(a, b=0): # default parameter
return a + b
def info(*args, **kwargs): # variable arguments
print(args) # tuple of positional args
print(kwargs) # dict of keyword args
# Lambda functions
square = lambda x: x**2
add = lambda x, y: x + y
Decorators
def decorator(func):
def wrapper(*args, **kwargs):
print("Before")
result = func(*args, **kwargs)
print("After")
return result
return wrapper
@decorator
def say_hello():
print("Hello!")
Object-Oriented Programming
Classes
class Person:
# Class variable
species = "Homo sapiens"
def __init__(self, name, age):
# Instance variables
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}"
def __str__(self):
return f"Person({self.name}, {self.age})"
# Create instance
p = Person("Alice", 30)
print(p.greet())
print(p)
# Inheritance
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
File Handling
# Read file
with open("file.txt", "r") as f:
content = f.read() # read entire file
lines = f.readlines() # list of lines
for line in f: # iterate lines
print(line.strip())
# Write file
with open("file.txt", "w") as f:
f.write("Hello\n")
f.writelines(["Line 1\n", "Line 2\n"])
# Append
with open("file.txt", "a") as f:
f.write("Appended text\n")
# JSON
import json
data = {"name": "Alice", "age": 30}
json.dumps(data) # to string
json.loads('{"name": "Alice"}') # from string
with open("data.json", "w") as f:
json.dump(data, f) # to file
with open("data.json", "r") as f:
data = json.load(f) # from file
Error Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError as e:
print(f"Value error: {e}")
except Exception as e:
print(f"Error: {e}")
else:
print("No error occurred")
finally:
print("Always executes")
# Raise exceptions
raise ValueError("Invalid value")
Common Built-in Functions
Math
abs(-5) # 5
min(1, 2, 3) # 1
max(1, 2, 3) # 3
sum([1, 2, 3]) # 6
round(3.14159, 2) # 3.14
pow(2, 3) # 8
Sequences
len([1, 2, 3])
sorted([3, 1, 2])
reversed([1, 2, 3])
enumerate(["a", "b"])
zip([1, 2], ["a", "b"])
all([True, False])
any([True, False])
Type Checking
type(x)
isinstance(x, int)
Useful Modules
Math
import math
math.pi # 3.141592...
math.ceil(3.2) # 4
math.floor(3.8) # 3
math.sqrt(16) # 4.0
math.factorial(5) # 120
Random
import random
random.random() # random float [0.0, 1.0)
random.randint(1, 10) # random int [1, 10]
random.choice([1, 2, 3]) # random element
random.shuffle(lst) # shuffle list in place
random.sample(lst, 3) # pick 3 unique elements
Datetime
from datetime import datetime, timedelta
now = datetime.now()
today = datetime.today()
dt = datetime(2024, 12, 25, 10, 30)
now.year # 2024
now.strftime("%Y-%m-%d") # "2024-12-25"
datetime.strptime("2024-12-25", "%Y-%m-%d")
# Timedelta
tomorrow = now + timedelta(days=1)
week_ago = now - timedelta(weeks=1)
Collections
from collections import Counter, defaultdict, deque
# Counter
c = Counter([1, 1, 2, 3, 3, 3])
c.most_common(2) # [(3, 3), (1, 2)]
# defaultdict
d = defaultdict(int) # default value is 0
d["key"] += 1 # no KeyError
# deque (double-ended queue)
dq = deque([1, 2, 3])
dq.append(4) # add to right
dq.appendleft(0) # add to left
dq.pop() # remove from right
dq.popleft() # remove from left
Itertools
from itertools import combinations, permutations, product
list(combinations([1, 2, 3], 2)) # [(1,2), (1,3), (2,3)]
list(permutations([1, 2, 3], 2)) # [(1,2), (1,3), (2,1), ...]
list(product([1, 2], ["a", "b"])) # [(1,'a'), (1,'b'), ...]
Comprehensions
# List comprehension
[x**2 for x in range(10)]
[x for x in range(20) if x % 2 == 0]
[x if x > 0 else 0 for x in range(-5, 5)]
# Dict comprehension
{x: x**2 for x in range(5)}
{k: v.upper() for k, v in dict.items()}
# Set comprehension
{x % 3 for x in range(10)}
# Generator expression (memory efficient)
(x**2 for x in range(1000000))
Common Patterns
Swap variables
a, b = b, a
Multiple assignment
x, y, z = 1, 2, 3
Check if empty
if not my_list:
# preferred
Get with default
value = dictionary.get(
"key", "default"
)
Chaining comparisons
if 0 < x < 10:
print("x is between
0 and 10")
Walrus operator (3.8+)
if (n := len(items)) > 5:
print(f"List has
{n} items")
Bestseller #1
Bestseller #2
Bestseller #3
Bestseller #4
Bestseller #5
Bestseller #6
Bestseller #7
Bestseller #8

