Search code examples
pythonpython-itertoolsiterable-unpacking

Convert a list of tuples (from itertools) into a list of words in a text file, Python


I'm using:

list(it.permutations(wordlist, 3))

and am getting a result as a list of tuples, such as:

[('mom', 'dad', 'kid'), ('mom', 'dad', 'house'), ('mom', 'dad', 'car'), ('mom', 'dad', 'happy'), ('mom', 'dad', 'Hello'), ('mom', 'dad', 'goodbye'), ('mom', 'dad', 'covid'), ('mom', 'dad', 'influenza'), ('mom', 'dad', 'cold'), ('mom', 'dad', 'car'), ('mom', 'dad', 'escape')...]

but what I really want is a .txt file like:

mom dad kid\n
mom dad house\n
mom dad car\n
... etc

How do I either iterate permutations straight into human readable rows, or write/convert this existing list into a file? THANKS (first question ever!)


Solution

  • with open('path/to/output', 'w') as outfile:
        for sent in it.permutations(wordlist, 3):
            outfile.write(f"{' '.join(sent)}\n")