Python IndentationError: Tabs vs Spaces

Python throws IndentationError or TabError and the code looks perfectly lined up. The culprit is invisible: tabs and spaces mixed together. Here's how to see it and stop it for good.

BytExplorer 4 min read July 1, 2026

Python stops before it even runs your code:

IndentationError: unexpected indent

or the closely related:

TabError: inconsistent use of tabs and spaces in indentation

Unlike most languages, Python uses indentation to define blocks — so whitespace is syntax. The maddening part is that the problem is usually invisible: a line indented with a tab looks identical on screen to one indented with spaces, but to Python they're different, and mixing them inside one block is an error.

Why it happens

You copy a snippet from a website or another file, paste it into code you indented with spaces, and the pasted line arrives with a tab. Everything lines up visually; Python sees two incompatible indentation styles and refuses.

Step 1: Make the whitespace visible

You can't fix what you can't see. Turn on whitespace rendering in your editor (VS Code: View → Render Whitespace), and tabs show as arrows, spaces as dots. The odd line jumps out immediately.

Step 2: Convert the file to spaces

The Python community standard (PEP 8) is 4 spaces, never tabs. Most editors convert in one action — in VS Code, click the indentation indicator in the status bar and choose Convert Indentation to Spaces.

# spot tab characters from the terminal if you prefer:
grep -Pn '\t' myscript.py

Step 3: Stop it happening again

Set your editor to insert spaces when you press Tab, so the mix can never form:

# VS Code settings.json
"editor.insertSpaces": true,
"editor.tabSize": 4,
"editor.detectIndentation": false

Pick spaces and never look back. The rule isn't "spaces are better than tabs" — it's that mixing them is what breaks, and standardising on one removes the whole class of error.

The checklist

  1. Turn on render whitespace to see tabs vs spaces.
  2. Convert the file to 4 spaces.
  3. Set the editor to insert spaces on Tab (insertSpaces: true).
  4. grep -Pn '\t' file.py to catch stray tabs from the terminal.
Put it into practice

Stop reading, start building

This pairs with a hands-on BytExplorer course — do it on your own machine and actually keep the skill.

More in Troubleshooting