The number of statically nested blocks in Python is limited to 20.
That is, nesting 19 for
loops will be fine (although excessively time consuming; O(n^19
This has to do with the blockstack, which is a stack of the byte code addresses, and is used to execute code blocks such as loops and exceptions.
It just so happens that a version of C (older than C99) had set this limit to 20
, and since the CPython interpreter is built with C, the same convention has been followed:
#define CO_MAXBLOCKS 20 /* Max static block nesting within a function */
The constant 20
seems to be set out of convention, and nothing more.
[Links courtesy Christian Dean.]
If the argument of convention isn't convincing, then take a look at The Zen of Python:
In [4]: import this
The Zen of Python, by Tim Peters
...
Flat is better than nested.
...
Since this value is a hardcoded constant, the only way to change it to effect in your programs is to rebuild your python distribution and run your script on the new build.
Download the cpython source code from github
Navigate to cpython/Include/code.h
Change the value of CO_MAXBLOCKS
to anything greater than 20
Recompile Python (disable tests, they'll complain)