Use this checklist when writing, reviewing, debugging, or refactoring Python code. Goal: avoid common semantic mistakes in indexing, mutability, assignment, function calls, iteration, comparison, and imports.
Python code should be reasoned from these principles:
name binding > object copying
mutable object > in-place side effects
half-open intervals > stop excluded
truthiness > explicit boolean conversion not always needed
identity != equality
Python slices use:
a[start:stop]Meaning:
include start
exclude stop
So:
a[i : i + 10]accesses indices:
i <= k < i+10
It does not access i+10.
range(n)produces:
0, 1, ..., n-1
Not n.
a[-1]means:
last element
Common patterns:
a[-1] # last item
a[:-1] # all except last item
a[-2:] # last two itemsa[100:200]returns:
[]But:
a[100]raises:
IndexErrora[::-1]returns a reversed copy.
b = ameans:
bind name b to same object as a
It does not create a new object.
Risk:
a = [1, 2]
b = a
b.append(3)
# a is now [1, 2, 3]b = a.copy()
b = a[:]For nested structures, shallow copy may still share inner objects.
Use:
import copy
b = copy.deepcopy(a)when independent nested objects are required.
Examples:
list
dict
set
a = [1, 2]
a.append(3)Examples:
int
float
str
tuple
frozenset
s = "abc"
s[0] = "x" # TypeErrorCreate a new object instead:
s = "x" + s[1:]Methods that mutate objects usually return:
NoneExample:
a = [3, 1, 2]
a.sort()Correct.
Avoid:
a = a.sort()because a becomes:
NoneCommon in-place methods:
list.append()
list.extend()
list.sort()
list.reverse()
dict.update()
set.add()
Avoid mutable default values:
def f(x, bag=[]):
bag.append(x)
return bagProblem:
same list reused across calls
Use:
def f(x, bag=None):
if bag is None:
bag = []
bag.append(x)
return bagPython treats empty values as false.
False-like values:
None
False
0
0.0
""
[]
()
{}
set()
Preferred:
if items:
...Instead of:
if len(items) > 0:
...Use explicit checks when meaning matters:
if x is None:
...not:
if not x:
...when 0, "", or [] are valid values.
and and or return operands, not always booleans.
value = user_input or default_valueMeaning:
if user_input is truthy, use user_input
else use default_value
Examples:
"hello" or "world" # "hello"
"" or "world" # "world"
"hello" and "world" # "world"
"" and "world" # ""a == bmeans:
same value
a is bmeans:
same object
Example:
a = [1, 2]
b = [1, 2]
a == b # True
a is b # FalseUse identity for None:
if x is None:
...Avoid:
if x == None:
...Python supports mathematical comparison chains:
1 < x < 10Meaning:
1 < x and x < 10Preferred for range checks.
+= may mutate in place.
For lists:
a = [1, 2]
b = a
a += [3]
# both a and b see [1, 2, 3]For immutable objects:
x = (1, 2)
x += (3,)creates a new tuple.
Agent rule:
check object mutability before using +=
Avoid this for nested lists:
matrix = [[0] * 3] * 3Problem:
inner lists share same reference
Use:
matrix = [[0] * 3 for _ in range(3)]Prefer direct iteration:
for item in items:
...Use enumerate when index is needed:
for i, item in enumerate(items):
...Avoid unnecessary index loops:
for i in range(len(items)):
...unless index arithmetic is required.
Dictionary lookup is by key, not position.
d["name"]Use safe access when key may be missing:
d.get("name")
d.get("name", default_value)Use membership check when needed:
if "name" in d:
...Functions can be:
assigned
passed as arguments
returned from functions
stored in data structures
Example:
def square(x):
return x * x
f = square
f(5)Useful for callbacks, decorators, strategies, and higher-order functions.
b = [x * 2 for x in a]creates a new list.
It does not mutate a.
Use comprehension for transformation. Use loops or in-place methods for mutation.
A module is usually executed once per Python process, then cached in:
sys.modulesUse:
if __name__ == "__main__":
main()to prevent script logic from running during import.
Before finalizing Python code, verify:
[ ] Slice stop index intentionally excluded
[ ] range stop value intentionally excluded
[ ] negative indices are intentional
[ ] slicing vs indexing error behavior considered
[ ] assignment does not accidentally share mutable objects
[ ] copy / deepcopy used when needed
[ ] mutable default arguments avoided
[ ] in-place methods not assigned back accidentally
[ ] truthiness does not hide valid values like 0 or ""
[ ] is used only for identity checks, especially None
[ ] == used for value equality
[ ] += does not create unwanted mutation
[ ] nested list multiplication avoided
[ ] enumerate used when index is needed
[ ] dict keys handled safely
[ ] import side effects controlled with __main__ guard
When uncertain, ask:
Am I creating a new object, or mutating / referencing an existing object?
This single question prevents most Python semantic bugs.