Search code examples
pythonloopsiteratorpermutationdelimiter

how to generate first n permutations then pause and restart?


Simple question i have the code from how to skim itertools permutations:

from itertools import permutations
ListX=["A","B","C","(",")","#"]
perm_iterator = list(permutations(ListX))
print(list(perm_iterator))

how do i pause, resume,stop, restart the iterations?

how do i see the iterations in steps of 100?

in steps of n?


Solution

  • You can get an infinitely looping copy of an iterator then take chunks of n from it using cycle and islice from itertools.

    import itertools
    
    n_chunks = 30
    chunk_size = 100
    l = ["A","B","C","(",")","#"]
    
    perm_iterator = itertools.permutations(l)
    loop_perms = itertools.cycle(perm_iterator)
    for n in range(n_chunks):
        print(list(itertools.islice(loop_perms, chunk_size)))