The whole point of itertools
is that values are produced lazily and not as lists. You don't need to change the code of permutations
, all you need to do is loop over the permutations as they are produced and then write them to a file.
for p in permutations(your_iterable):
# your code to write p to a file here
Note that at no point there's a list involved in this code. permutations(your_iterable)
is an iterator you can explicitly pull values out of with next
or implicitly by employing a for
loop.
it is a very large amount of permutations and causes a memory error
I am trying to tell you that permutations(your_iterable)
can never produce a memory error in any non-artificially-contrived scenario if you don't explicitly make a list out of permutations(your_iterable)
yourself. The iterator produces one permutation at a time which you can write to a file without ever holding all permutations in RAM.
I am passing a list of length 110 to itertools.permuations
This is not a problem with the standard library or values in RAM.
Your code will produce
15882455415227429404253703127090772871724410234473563207581748318444567162948183030959960131517678520479243672638179990208521148623422266876757623911219200000000000000000000000000
permutations. There is no file system on the planet with enough storage space to write these permutations to.
Also, there's not enough time left until the heat death of the universe to compute all these permutations, even if you could compute one in a nanosecond.
>>> from math import factorial
>>> factorial(110)/(10E9*3600*24*365)
>>> 5.0362935740827724e+160 # years
4 is the second parameter for permutations
Ok, in that case your file would require around 1.7 GiB of space if you stored each permutation as a string of minimum length 13 akin to '(0, 1, 2, 3)\n'
with one byte per character.
>>> perms = sum(1 for _ in permutations(list(range(110)), 4))
>>> perms*13/(2**30)
>>> 1.677529625594616
That's manageable - but it could require much more space if the objects in your list had longer string representations. We can't tell you why you get a memory error without seeing your code.