Unindent does not match any outer indentation level (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 30, 2022

banner

Photo from Unsplash

Unindent does not match any outer indentation level (Python) #

The Python "IndentationError: unindent does not match any outer indentation level" occurs when we mix tabs and spaces in the same code block. To solve the error, remove the spacing and only use tabs or spaces, but don't mix the two in the same code block.

indentationerror unindent does not match any outer indentation level

Here is an example of how the error occurs.

main.py
# ⛔️ IndentationError: unindent does not match any outer indentation level if len('hi') == 2: print('a') print('b')

The first line in the code block was indented using tabs, and the second - using spaces.

mixing tabs and spaces

The screenshot shows that the print('a') line was indented using tabs, and the print('b') line was indented using spaces.

To solve the error, remove the whitespace and only indent the lines in the code block using tabs or using spaces.

Your error message should show the exact location where the error is raised, so you can remove the whitespace and consistently indent the lines in the code block using tabs or spaces.

indentationerror unindent does not match any outer indentation level

If you use VSCode, you can solve the error by using the "Convert indentation to spaces" or "Convert indentation to tabs" commands:

  1. press CTRL + Shift + P or ( + Shift + P on Mac) to open the command palette.
  2. type: "convert indentation to"
  3. Select your preferred option
  4. Save the file

vscode convert indentation to

If you use VSCode, you can show whitespace characters by:

  1. pressing CTRL + Shift + P or ( + Shift + P on Mac) to open the command palette.
  2. typing "open workspace settings"
  3. typing renderwhitespace
  4. setting it to all

vscode render whitespace

If you render whitespace characters in your IDE, tabs should show as arrows and spaces should show as dots.

mixing tabs and spaces

It is a matter of personal preference if you use only tabs or only spaces, but make sure not to mix the two.

Note that if you use tabs in one code block and spaces in the other, you won't get an error.

The error is only raised if you mix tabs and spaces in the same code block.

only using tabs or spaces

The upper if statement uses tabs for indentation, and the lower uses spaces.

The example doesn't cause an error because we didn't mix tabs and spaces in the same code block.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.