Skip to content

Python's traps

Guess the output · 1 of 4

Dividing negatives

1print(-7 // 2, -7 % 2)

What does this print?

Read this lesson as text

Four things Python does that surprise people, and AI code.

Dividing negatives

print(-7 // 2, -7 % 2)

What does this print?

  • -4 1
  • -3 -1
  • -3 1
Show the answer

-4 1 // rounds *down* (towards minus infinity), so -3.5 becomes -4, and the remainder is then 1. Code ported from C++ or Java, where -7 / 2 is -3, breaks here.

Rounding halves

print(round(2.5), round(3.5))

What does this print?

  • 3 4
  • 2 3
  • 2 4
Show the answer

2 4 Python rounds halves to the nearest *even* number: 2.5 → 2, 3.5 → 4. It's on purpose (it avoids bias), but it surprises everyone once.

One row, twice

g = [[0] * 2] * 2
g[0][0] = 1
print(g)

What does this print?

  • [[1, 0], [0, 0]]
  • [[1, 0], [1, 0]]
  • [[1, 1], [0, 0]]
Show the answer

[[1, 0], [1, 0]] * 2 on the outer list copies the *same* row twice, so changing one changes both. Build grids with [[0] * 2 for _ in range(2)].

A list that remembers

def add(x, items=[]):
    items.append(x)
    return items

add(1)
print(add(2))

What does this print?

  • [2]
  • [2, 1]
  • [1, 2]
Show the answer

[1, 2] The default [] is made once, when the function is defined, and shared by every call. Use items=None and create the list inside.