ZeroDivisionError in Python — What It Means and How to Fix It

What Python's ZeroDivisionError exception means and how to resolve it.

Published October 27, 2026

ZeroDivisionError is raised when you divide or take a modulo by zero.

What it means and why it happens

It happens with 1/0, x % 0 and averages over empty lists.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
ZeroDivisionError: division by zero

Practical examples

Code that triggers it

avg = sum(nums) / len(nums)   # empty list

The fix

avg = sum(nums) / len(nums) if nums else 0

Safe helper

def safe_div(a, b, default=0):
    return a / b if b else default

Common mistakes

  • Averages of empty lists.
  • Catching and hiding it instead of handling the case.
  • Float vs integer division confusion.

Key takeaways

  • ZeroDivisionError: ZeroDivisionError is raised when you divide or take a modulo by zero.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

Does float division by zero raise?

Yes in Python; NumPy returns inf with a warning.

How do I find which line caused ZeroDivisionError?

The error message and stack trace show the file and line; start there and work backwards.

More Python articles