This is a common problem, not a Python specific one. In most languages, even when iterators are used to use structures, the entire structure is stored in memory. Thus, iterators are mainly used as โfunctionalโ tools, and not as memory optimization tools.
In python, many people use large memory due to the presence of really large structures (dictionaries, etc.). However, all program object variables will be stored in memory in any way. The only solution is to serialize the data (saving to the file system, database, etc.).
So, in your case, you can create a custom function that will create a list of permutations. But instead of adding each permutation element to the list, he saved the element either in a file (or in a database with the corresponding structure). Then you can get one at a time each permutation from a file (or database), without bringing the entire list to memory.
However, as mentioned earlier, you always need to know which permutation you are currently in. To avoid extracting all the created permutations from the database (which would create the same bottleneck), you could have an index for each location containing the character used in the previously generated permutation (and create permutations that add characters and a predefined sequence).
source share