Spaces vs Tabs: The Great Python Debate

tabs vs spaces the great python debate

If you've ever used the Python language, you'll know that it is very particular about whitespace and indentation! Each nested block of code needs to be indented 4 spaces in from the last block of code, which is equivalent to a tab - or is it?

Python documentation, more specifically the PEP8 style guide, states that spaces should be used, and if you end up accidentally switching between spaces and tabs in your code Python 3 will throw a TabError. So why is this?

After doing some digging I found a Reddit thread that explains that a tab is actually a single character, despite it taking up the length of four spaces - check out the gif below to see what I mean - the first line is a tab, which when we use the arrow to move back is one character. The second line is 4 spaces, which are 4 separate characters that we can move back through individually.

Example of tabs vs spaces characters

This can cause issues when different IDE's interpret the characters differently to your IDE, or working within a team where some people tab and some people space - Madness and lots of errors!

Thankfully there is a workaround 🥳 Most IDE's allow you to customise your tab size, allowing you to specify the number of spaces a tab is equal to.

To adjust this in VSCode, open the settings and search for:

Editor: Tab Size

You can then adjust this to use 4 spaces each time you tab within a file. You can also adjust this in the settings.json file and configure the tab size for different languages - read more about this in my article Configure spacing in VSCode by Language

Let me know what camp you fall into in the comments below, and have a giggle at the clip below from Silicon Valley about tabs versus spaces 🤣

Avatar for Kera Cudmore

Written by Kera Cudmore

Junior Software Developer at the Met Office | Code Institute Alumna.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.