Search code examples
pythonprintingformatpython-itertools

Formatting print from itertools permutations


I picked up from an old post here that it is not possible to print the results of an itertools.permutations except by converting to a list first. This is what I did here:

import itertools

p = itertools.permutations('ABCD', 2)

print(list(p))

I get the following output (in Jupyter Notebook):

[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'A'), ('B', 'C'), ('B', 'D'), ('C', 'A'), ('C', 'B'), ('C', 'D'), ('D', 'A'), ('D', 'B'), ('D', 'C')]

I picked up the original example from itertools from docs.python.org. The example section on that page shows the output as:

AB AC AD BA BC BD CA CB CD DA DB DC

That same page doesn't actually explain how to use itertools, having to import the module or how to get the output, so do I take it also that although it shows that output in a conveniently readable format, it was not produced in code but just typeset this way?

Either way, is there a way to tweak that print command to produce the same format as above?

Thank you for your comments and suggestions.

All the best. c


Solution

  • Here is what you can do:

    import itertools
    
    p = itertools.permutations('ABCD', 2)
    
    print(' '.join([a+b for a,b in p]))
    

    Output:

    AB AC AD BA BC BD CA CB CD DA DB DC